簡體   English   中英

Pandas:檢查json對象中是否存在dataframe列

[英]Pandas: Check if dataframe column exists in the json object

我有一個名為'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'列的pandas數據框:

Country
--------
AU
AL
DZ

如何檢查“國家/地區”列中的任何行是否存在於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')

由於您已經有一個pandas 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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM