Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Switch column values by condition in pandas

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I guess I should use something like :

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

 np.where(.... 

>Solution :

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']])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading