如何在Pandas中的条件下将第1列的值与第2列的值交换



如果熊猫中的column1.value >= 14,我想将column1值与column2值交换!

col1 col2
16 1
3 2
4 3

使用Series.mask并重新分配两列值:

m = df["col1"].ge(14)
out = df.assign(
col1=df["col1"].mask(m, df["col2"]),
col2=df["col2"].mask(m, df["col1"])
)

输出:

col1  col2
0     1    16
1     3     2
2     4     3

简单的一行式解决方案,

df.loc[df['col1'] >= 14,['col1','col2']] = df.loc[df['col1'] >= 14,['col2','col1']].values

最新更新