I want to compare country list with column data which is dictionary object type in pandas dataframe Python

Viewed 93
list = ['Japan', 'France', 'United States']

want to compare list with column name place key 'country' and value '' get only those rows which have countries similar to countries in list

the dataframe look like this:

Id        Place
767       {'country_code': 'US','country': 'United States'}
645       {'country_code': 'IRL','country': 'Ireland'}
324       {'country_code': 'JAP','country': 'Japan'}

i have used this:

 for i in range(0,len(df['place'])):
      df['place'][0]["country"].isin(list)
1 Answers

Use, Series.str.get along with Series.isin to create a boolean mask then filter the rows using this mask:

m = df['Place'].str.get('country').isin(lst)
df = df[m]

# print(df)
    Id                                              Place
0  767  {'country_code': 'US', 'country': 'United States'}
2  324        {'country_code': 'JAP', 'country': 'Japan'}
Related