交换熊猫中选定行的列值

时间:2019-10-14 17:16:09

标签: python pandas numpy jupyter-notebook

我需要清理数据集,由于b不能大于a,所以交换了它们的值,所以有些列有错误,我创建了一个名为wrong_data的列并且只要发生这种情况,它就具有True值:

   df['wrong_data'] =  (df['a'] < df['b'] )

现在,我想在条件满足时ab中交换数据,所以只要wrong_data = true成立就可以交换数据。

到目前为止,我已经尝试过:

df.at[wrong_data = true, 'a'] = b
df.at[wrong_data = true, 'b'] = a

但是显然语法是错误的,我不确定如何处理。

3 个答案:

答案 0 :(得分:0)

欢迎使用StackOverflow!

我认为您可以省略第三列。您是否尝试过以下方法:

wrongDataIdx = (df['a'] < df['b'])
df.loc[wrongDataIdx, ['a', 'b']] = df.loc[wrongDataIdx, ['b', 'a']].values

这应该可以解决您的问题。很高兴听到一些建设性的反馈!

已测试:

>>> df = pd.DataFrame({'a': [1,2,3], 'b': [4,3,2]})
>>> wrongDataIdx = (df['a'] < df['b'])
>>> df.loc[wrongDataIdx, ['a', 'b']] = df.loc[wrongDataIdx, ['b', 'a']].values
>>> df
a  b
0  4  1
1  3  2
2  3  2

答案 1 :(得分:0)

您还可以使用几个np.where语句:

df['a'] = np.where(df['wrong_data'] == True, 'b', 'a')
df['b'] = np.where(df['wrong_data'] == True, 'a', 'b')

答案 2 :(得分:0)

您不需要wrong_data列。

尝试一下:

df[["a", "b"]]=df.apply(lambda x: pd.Series(sorted([x.a, x.b])), axis=1)

样本输入:

import pandas as pd

df=pd.DataFrame(data={"a": [1,5,7,9,11], "b": [2,3,10,-6,2]})

print(df)

df[["a", "b"]]=df.apply(lambda x: pd.Series(sorted([x.a, x.b])), axis=1)

print(df)

输出:

  a   b
0   1   2                                                   
1   5   3                                                   
2   7  10                                                   
3   9  -6                                                   
4  11   2                                                      
  a   b                                                    
0  1   2                                                    
1  3   5                                                    
2  7  10                                                    
3 -6   9                                                    
4  2  11                                                   
 [Program finished]