我有一个名为“countries”的json对象,如下所示,所有国家都有ISO代码列表:
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"}]我有一个“国家”专栏的熊猫数据栏:
Country
--------
AU
AL
DZ如何检查'Country‘列中的任何行是否存在于json对象的'alpha-2’列中,如果不存在则打印错误?
当我尝试下面的代码时,我不会发现任何错误,也不会打印任何内容。
if df['Country'].any() in [x['alpha-2'] for x in countries]:
print "Country code exists"发布于 2018-11-09 19:51:10
你可以
if set(x['alpha-2'] for x in countries).intersection(df.Country):
print('Country code exists')或者,在精神上更接近你正在尝试的东西(但性能特征完全不同),
if df.Country.isin(x['alpha-2'] for x in countries).any():
print('Country code exists')发布于 2018-11-09 19:57:20
因为您已经有了一个熊猫DataFrame,所以可以将JSON对象转换为DataFrame,使用pd.merge对两者进行inner连接,然后检查返回的DataFrame是否为空。
>>> 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')https://stackoverflow.com/questions/53232374
复制相似问题