根据熊猫中的条件交换列值

时间:2019-06-03 05:48:21

标签: python pandas dataframe

我想按条件重新定位列。 如果国家是“日本”,我需要将last_name和first_name反向放置。

df = pd.DataFrame([['France','Kylian', 'Mbappe'],
               ['Japan','Hiroyuki', 'Tajima'],
               ['Japan','Shiji', 'Kagawa'],
               ['England','Harry', 'Kane'],
               ['Japan','Yuya', 'Ohsako'],
               ['Portuguese','Cristiano', 'Ronaldo']],
              columns=['country', 'first_name', 'last_name'])

当前输出为

      country first_name last_name
0      France     Kylian    Mbappe
1       Japan   Hiroyuki    Tajima
2       Japan      Shiji    kagawa
3     England      Harry      Kane
4       Japan       Yuya    Ohsako
5  Portuguese  Cristiano   Ronaldo

我想跟随它。

      country first_name last_name
0      France     Kylian    Mbappe
1       Japan     Tajima  Hiroyuki
2       Japan     Kagawa    Shinji
3     England      Harry      Kane
4       Japan     Ohsako      Yuya
5  Portuguese  Cristiano   Ronaldo

有什么主意吗?

4 个答案:

答案 0 :(得分:4)

使用loc并将“名字”和“姓氏”值交换为“国家”与“日本”匹配的行。

m = df['country'] == 'Japan'

df.loc[m, ['first_name', 'last_name']] = (
    df.loc[m, ['last_name', 'first_name']].values)
df    

      country first_name last_name
0  France      Kylian     Mbappe  
1  Japan       Tajima     Hiroyuki
2  Japan       Kagawa     Shiji   
3  England     Harry      Kane    
4  Japan       Ohsako     Yuya    
5  Portuguese  Cristiano  Ronaldo 

使用renameupdate的另一个选项:

mp = {'first_name': 'last_name', 'last_name': 'first_name'}
df.update(df.loc[m].rename(mp, axis=1))
df

      country first_name last_name
0  France      Kylian     Mbappe  
1  Japan       Tajima     Hiroyuki
2  Japan       Kagawa     Shiji   
3  England     Harry      Kane    
4  Japan       Ohsako     Yuya    
5  Portuguese  Cristiano  Ronaldo 

答案 1 :(得分:1)

### check below   


 df['first_name'],df['last_name']=np.where(df['country']=='Japan',(df['last_name'],df['first_name']),(df['first_name'],df['last_name']))

输出:

   country      first_name     last_name
0   France      Kylian         Mbappe
1   Japan       Tajima         Hiroyuki
2   Japan       Kagawa         Shiji
3   England     Harry          Kane
4   Japan       Ohsako         Yuya
5   Portuguese  Cristiano  Ronaldo

答案 2 :(得分:0)

使用np.where

mask = df['country']=='Japan'

df['first_name1'] = np.where(mask, df['last_name'], df['first_name'])
df['last_name'] = np.where(mask, df['first_name'], df['last_name'])

df['first_name'] = df['first_name1']

df.drop('first_name1', axis=1, inplace=True)

输出:

    country first_name  last_name
0   France  Kylian  Mbappe
1   Japan   Tajima  Hiroyuki
2   Japan   Kagawa  Shiji
3   England Harry   Kane
4   Japan   Ohsako  Yuya
5   Portuguese  Cristiano   Ronaldo

答案 3 :(得分:0)

尝试一下:

df['last_name1']=df.last_name
df.loc[df.country=='Japan','last_name']=df[df.country=='Japan']['first_name']
df.loc[df.country=='Japan','first_name']=df[df.country=='Japan']['last_name1']
df=df.drop(['last_name1'],axis=1)