我有一个名为“国家”的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
如何检查json对象的“国家/地区”列中是否有任何行存在于json对象的“ alpha-2”列中,并显示错误(如果不存在)?
当我尝试下面的代码时,我没有得到任何错误,也没有输出任何内容。
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')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句