如何在Pandas中将数据从一列交换到另一列



我正试图弄清楚如何在两列之间交换数据。b列中的数据应在d列中。

例如:

col a    col b    col c   col d
1982     38      M        Late   
1983     37      F        Early  
1984    Late     M        36 

如何将第3行中的值仅交换为这两列?

提前感谢

使用np.where(Condition, outcomeIfConditionTrue, outcomeIfConditionFalse)。将其与用a,b=b,a表示的python的交换相结合

df['col b'],df['col d']=np.where(df['col a'].eq(1984),df['col d'],df['col b']),np.where(df['col a'].eq(1984),df['col b'],df['col d'])
print(df)

col a  col b  col c col d
0  1982   38    M   Late
1  1983   37    F  Early
2  1984   36    M   Late

最新更新