Faust_ARP32
Faust_ARP32

Reputation: 25

How to Swap data from one column to another in Pandas

I'm trying to figure out how I can swap data bewteen two columns. The data in col b should be in col d.

EX:

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

How would I swap the values in row 3, for only those two columns?

Thanks in advance

Upvotes: 0

Views: 72

Answers (1)

wwnde
wwnde

Reputation: 26676

Use np.where(Condition, outcomeIfConditionTrue, outcomeIfConditionFalse). Combine this with python's interchange denoted by a,b=b,a

    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

Upvotes: 2

Related Questions