Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: Check if dataframe column exists in the json object

I have a json object called 'countries' like below with all the countries ISO code list:

countries = [{"name":"Afghanistan","alpha-2":"AF","country-code":"004"},{"name":"Åland Islands","alpha-2":"AX","country-code":"248"},{"name":"Albania","alpha-2":"AL","country-code":"008"},{"name":"Algeria","alpha-2":"DZ","country-code":"012"}]

I have a pandas dataframe with 'Country' column:

Country
--------
AU
AL
DZ

How can I check if any row in 'Country' column exists in 'alpha-2' column of the json object and print error if it does not exist?

When I try the below code, I don't get any error nor does it print anything.

if df['Country'].any() in [x['alpha-2'] for x in countries]:
    print "Country code exists"
like image 416
Raj Avatar asked Dec 11 '25 06:12

Raj


1 Answers

You could do

if set(x['alpha-2'] for x in countries).intersection(df.Country):
    print('Country code exists')

or, closer in spirit to what you are trying (but with completely different performance characteristics),

if df.Country.isin(x['alpha-2'] for x in countries).any():
    print('Country code exists')
like image 148
fuglede Avatar answered Dec 13 '25 19:12

fuglede