如何在大熊猫不相等的值上将数据从一列移动到另一列?

时间:2017-04-10 09:44:28

标签: python pandas

我在一个数据框中有两列'名字'和'首选名称'。如果首选名称与名字不同,我想将该值移动到名字。 e.g:

   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  

2 个答案:

答案 0 :(得分:0)

有点不耐烦,所以我做了'丑'的方式。查询名称不同的索引的数据,然后将它们添加到这些值上

Intent intent = new Intent( SplashScreen.this, MainActivity.class);

答案 1 :(得分:0)

最简单的只是指定为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

您可以先在差异中创建boolean掩码,然后按locmask添加新值:

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

另一种解决方案:

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