python - Pandas 有条件地交换两列中的值

标签 python pandas

我有一个包含两列的 Pandas DataFrame。在某些行中,列被交换。如果它们被交换,那么“a”列将为负数。检查这一点然后交换两列的值的最佳方法是什么。

def swap(a,b):
    if a < 0:
        return b,a
    else:
        return a,b

有什么方法可以使用 apply 与此函数来交换两个值吗?

最佳答案

试试这个?通过使用np.where

ary=np.where(df.a<0,[df.b,df.a],[df.a,df.b])
pd.DataFrame({'a':ary[0],'b':ary[1]})

Out[560]: 
   a  b
0  3 -1
1  3 -1
2  8 -1
3  2  9
4  0  7
5  0  4

数据输入:

df
Out[561]: 
   a  b
0 -1  3
1 -1  3
2 -1  8
3  2  9
4  0  7
5  0  4

并使用apply

def swap(x):
    if x[0] < 0:
        return [x[1],x[0]]
    else:
        return [x[0],x[1]]


df.apply(swap,1)
Out[568]: 
   a  b
0  3 -1
1  3 -1
2  8 -1
3  2  9
4  0  7
5  0  4

关于python - Pandas 有条件地交换两列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46332764/

相关文章:

python - 修改后的随机快速排序 - 不返回

python - djangorest框架用户注册

python - 覆盖 XML 文件

python - Python 3 OpenCV无法录制和保存视频

Python - pandas - 找到与平局解析最常见的组合 - 性能

python - set_axis() 获得参数 'axis' 的多个值

python - 用特殊字符过滤 df

python - Pandas :对行组而不是单个行进行排序

Python Pandas : How to drop the *correct* duplicate row?

python - 如何分组和计数