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"
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With