I'd like to swap column1 value with column2 value if column1.value >= 14
in pandas!
col1 | col2 |
---|---|
16 | 1 |
3 | 2 |
4 | 3 |
This should become:
col1 | col2 |
---|---|
1 | 16 |
3 | 2 |
4 | 3 |
Thanks!
CodePudding user response:
Use Series.mask
and re-assign the two columns values:
m = df["col1"].ge(14)
out = df.assign(
col1=df["col1"].mask(m, df["col2"]),
col2=df["col2"].mask(m, df["col1"])
)
Output:
col1 col2
0 1 16
1 3 2
2 4 3
CodePudding user response:
Simple one liner solution,
df.loc[df['col1'] >= 14,['col1','col2']] = df.loc[df['col1'] >= 14,['col2','col1']].values