0

I have a Dataframe with several column and below is first 3 columns in that dataframe:

data_df = pd.DataFrame({'id':['era','bb','cs','jd','ek','gtf','okg','huf','mji','loj','djjf','wloe','rfm','cok'],
                        'doc':[1050 ,580,170,8, 7, 220, 45155,305,458,201,48,78,256,358],
                       'dif':[1,1,1,3,3,2,2,3,4,5,8,7,9,10]})
data_df
    id    doc      dif
0   era   1050     1    
1   bb    580      1    
2   cs    170      1    
3   jd    8        3    
4   ek    7        3    
5   gtf   220      2    
6   okg   45155    2    
7   huf   305      3    
8   mji   458      4    
9   loj   201      5    
10  djjf  48       8    
11  wloe  78       7    
12  rfm   256      9    
13  cok   358      10

I want to change the values in "dif" column like the reverse. I mean I want to change 1 to 10, 2 to 9, 3 to 8,.... 10 to 1. How can I do that? I was trying to do that like below but then I couldn't figure which values to correct next time.

data_df.loc[(data_df.dif == 1),'dif']= 10
data_df['dif'].mask(data_df['dif'] == 2, 9, inplace=True)

Any help would be appreciated. Thanks in advance

1
  • 3
    11 - df['dif']... Commented Apr 26, 2021 at 15:36

3 Answers 3

2

Create a dict for mapping -

dict1 = dict(zip(range(1, 11), range(10,0,-1)))
data_df['dif'] = data_df['dif'].map(dict1)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Really appreciate it!
2
new_df = data_df.assign(dif=11 - data_df['dif'])

Or, if you want to do it in place:

data_df['dif'] = 11 - data_df['dif']

1 Comment

Thanks! Really appreciate it!
0

It's really simple:

>>> data_df["dif"] = 11 - data_df["dif"]
>>> data_df
      id    doc  dif
0    era   1050   10
1     bb    580   10
2     cs    170   10
3     jd      8    8
4     ek      7    8
5    gtf    220    9
6    okg  45155    9
7    huf    305    8
8    mji    458    7
9    loj    201    6
10  djjf     48    3
11  wloe     78    4
12   rfm    256    2
13   cok    358    1

or replace 11 by data_df["dif"].max() + 1

1 Comment

Thanks! Really appreciate it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.