我有一个名为“国家”的 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"}]
我有一个带有“国家/地区”列的 Pandas 数据框:
Country
--------
AU
AL
DZ
如何检查 json 对象的 'alpha-2' 列中是否存在 'Country' 列中的任何行,如果不存在则打印错误?
当我尝试下面的代码时,我没有收到任何错误,也没有打印任何内容。
if df['Country'].any() in [x['alpha-2'] for x in countries]:
print "Country code exists"
最佳答案
你可以做
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')
关于python - Pandas:检查 json 对象中是否存在 dataframe 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53232374/