简体   繁体   中英

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"

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')

Since you already have a pandas DataFrame, you could convert the JSON object into a DataFrame, do an inner join of both using pd.merge , and then check if the returned DataFrame is empty or not.

>>> import pandas as pd
>>> countries_base = [{'Country': 'AU'}, {'Country': 'AL'}, {'Country': 'DZ'}]
>>> 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"}]
>>> df1 = pd.DataFrame(countries_base)
>>> df2 = pd.DataFrame(countries)
>>> m = pd.merge(df1, df2, how='inner', left_on='Country', right_on='alpha-2')
>>> if m.empty:
>>>     print('Country code does not exist') 
>>> else:
>>>     print('Country code exists')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM