python - Pandas:检查 json 对象中是否存在 dataframe 列

标签 python pandas dataframe

我有一个名为“国家”的 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/

相关文章:

python - 如何使用 python 从 config.ini 文件中的选项获取嵌套值

python - 尝试在 Python 3 中将函数作为整数返回

python - 仅具有高亮值的 matplotlib 条形图

python - 将行追加到 CSV 文件

python - 为什么 `pandas.read_csv` 不是 `pandas.DataFrame.to_csv` 的倒数?

python - 将列与 pandas 中的常量值相乘。类型错误

python - 使用 feedparser 从博客中获取每个独特的项目。检查 for 循环中的列表成员身份不起作用

python - 通过与列表比较过滤掉 panda-df 的行

r - 如何在 R 中使用 igraph 选择图形顶点?

python - 如何在 Python 中使用 BLE 通知