Home > Software engineering >  Switch column values by condition in pandas
Switch column values by condition in pandas

Time:12-04

I have a dataframe such as :

COL1 COL2 Value 
A    B    -
C    D     
E    F     
G    H    -
I    J    -
K    L    -
M    N    -
O    P     

I would like to switch values between COL1 and COL2 when the column Value == "-".

Does someone have an idea ?

I guess I should use something like :

m = tab['Value'].eq('-')

 np.where(.... 

CodePudding user response:

UseDataFrame.loc with convert values to numpy array:

m = df['Value'].eq('-')

df.loc[m, ['COL1','COL2']] = df.loc[m, ['COL2','COL1']].to_numpy()
print (df)
  COL1 COL2 Value
0    B    A     -
1    C    D      
2    E    F      
3    H    G     -
4    J    I     -
5    L    K     -
6    N    M     -
7    O    P      

Or numpy.where with broadcasting mask:

m = df['Value'].eq('-')
df[['COL1','COL2']] = np.where(m.to_numpy()[:, None], 
                               df[['COL2','COL1']], 
                               df[['COL1','COL2']])
  • Related