简体   繁体   中英

Pandas How to replace values based on Conditions for Several Values

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

Create a dict for mapping -

dict1 = dict(zip(range(1, 11), range(10,0,-1)))
data_df['dif'] = data_df['dif'].map(dict1)
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']

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM