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 value between column based pandas

I have the following data frame:

     Name  Age      City Gender Country
0     Jane   23     NaN      F    London
1  Melissa   45     Nan      F    France
2     John   35     Nan      M   Toronto

I want to switch value between column based on condition:

if Country equal to Toronto and London

I would like to have this output:

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

   Name  Age      City  Gender Country
0     Jane   23     London   F     NaN   
1  Melissa   45     NaN      F    France
2     John   35     Toronto  M     NaN  

How can I do this?

>Solution :

I would use .loc to check the rows where Country contains London or Toronto, then set the City column to those values and use another loc statement to replace London and Toronto with Nan in the country column

df.loc[df['Country'].isin(['London', 'Toronto']), 'City'] = df['Country']
df.loc[df['Country'].isin(['London', 'Toronto']), 'Country'] = np.nan

output:

      Name  Age     City Gender Country
0     Jane   23   London      F     NaN
1  Melissa   45      NaN      F  France
2     John   35  Toronto      M     NaN
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