简体   繁体   中英

How do i move data from one column to another on values that aren't equal in pandas?

I have two columns in one data frame 'first name' and 'preferred name'. If the preferred name is different to first name, I want to move that value to first name. eg:

   First Name  Preferred Name  
1  David       Dave       
2  John        John        
3  Sarah       Sarah
4  Elizabeth   Liz



   First Name  Preferred Name  
1  Dave        Dave       
2  John        John        
3  Sarah       Sarah
4  Liz         Liz  

slightly impatient, so i did it the 'ugly' way. queried the data for indices where names are different, and then added them on those values

name_index = df[df['first name'] != df['preferred name']]
df.ix[name_index,'first name'] = df.ix[name_index,'preferred name']

The simpliest is only assign as pointed EdChum :

df['first name'] = df['preferred name']
print (df)
  first name preferred name
1       Dave           Dave
2       John           John
3      Sarah          Sarah
4        Liz            Liz

You can first create boolean mask where difference and then add new values by loc or by mask :

mask = df['first name'] != df['preferred name']
df.loc[mask, 'first name'] = df['preferred name']
print (df)
  first name preferred name
1       Dave           Dave
2       John           John
3      Sarah          Sarah
4        Liz            Liz

Another solution:

mask = df['first name'] != df['preferred name']
df['first name'] = df['first name'].mask(mask,df['preferred name'])
print (df)
  first name preferred name
1       Dave           Dave
2       John           John
3      Sarah          Sarah
4        Liz            Liz

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