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

How to assign new column based on the list of string values in pandas

I have a dataframe that one of the column contains string values, and I want to assign new column if this column values are in the list I specified.

my_list = [‘AA’, ‘TR’, ‘NZ’]

For example:
My dataframe : df

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

country
AA
TR
SG

The dataframe I want to have:

country flag
AA 1
TR 1
SG 0

I tried this one but I gave an Value Error.

df.assign(flag = lambda df: '1' if df['country'].isin(my_list) else '0')

What should I do? Thank you

>Solution :

You can directly convert your boolean to 0/1 with astype(int):

df.assign(flag= df['country'].isin(my_list).astype(int))

Or for a string:

df.assign(flag= df['country'].isin(my_list).astype(int).astype(str))

Alternatively, use numpy.where:

import numpy as np
df.assign(flag=np.where(df['country'].isin(my_list), '1', '0'))

output:

  country flag
0      AA    1
1      TR    1
2      SG    0
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