首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >熊猫:检查json对象中是否存在dataframe列

熊猫:检查json对象中是否存在dataframe列
EN

Stack Overflow用户
提问于 2018-11-09 19:47:11
回答 2查看 1.5K关注 0票数 3

我有一个名为“countries”的json对象,如下所示,所有国家都有ISO代码列表:

代码语言:javascript
复制
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"}]

我有一个“国家”专栏的熊猫数据栏:

代码语言:javascript
复制
Country
--------
AU
AL
DZ

如何检查'Country‘列中的任何行是否存在于json对象的'alpha-2’列中,如果不存在则打印错误?

当我尝试下面的代码时,我不会发现任何错误,也不会打印任何内容。

代码语言:javascript
复制
if df['Country'].any() in [x['alpha-2'] for x in countries]:
    print "Country code exists"
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-11-09 19:51:10

你可以

代码语言:javascript
复制
if set(x['alpha-2'] for x in countries).intersection(df.Country):
    print('Country code exists')

或者,在精神上更接近你正在尝试的东西(但性能特征完全不同),

代码语言:javascript
复制
if df.Country.isin(x['alpha-2'] for x in countries).any():
    print('Country code exists')
票数 4
EN

Stack Overflow用户

发布于 2018-11-09 19:57:20

因为您已经有了一个熊猫DataFrame,所以可以将JSON对象转换为DataFrame,使用pd.merge对两者进行inner连接,然后检查返回的DataFrame是否为空。

代码语言:javascript
复制
>>> 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')
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53232374

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档