我需要将JSON对象解析为DataFrame。对象的格式是这样的:
{"219": [{"year": "2015", "code": "VU", "category": "Vulnerable"},
{"year": "2008", "code": "VU", "category": "Vulnerable"},
{"year": "2002", "code": "VU", "category": "Vulnerable"},
{"year": "1996", "code": "VU", "category": "Vulnerable"},
{"year": "1994", "code": "V", "category": "Vulnerable"},
{"year": "1990", "code": "V", "category": "Vulnerable"},
{"year": "1988", "code": "V", "category": "Vulnerable"},
{"year": "1986", "code": "V", "category": "Vulnerable"}],
"561": [{"year": "2016", "code": "LC", "category": "Least Concern"},
{"year": "2010", "code": "LC", "category": "Least Concern"},
{"year": "2006", "code": "LC", "category": "Least Concern"},
{"year": "1996", "code": "EN", "category": "Endangered"},
{"year": "1994", "code": "R", "category": "Rare"},
{"year": "1990", "code": "R", "category": "Rare"},
{"year": "1988", "code": "R", "category": "Rare"},
{"year": "1986", "code": "R", "category": "Rare"}],
"571": [{"year": "2016", "code": "LC", "category": "Least Concern"},
{"year": "2008", "code": "LC", "category": "Least Concern"},
{"year": "2004", "code": "LC", "category": "Least Concern"},
{"year": "1996", "code": "LR/lc", "category": "Lower Risk/least concern"}]
}
最终,我希望DataFrame将键用作行,year
列(每年一列)和code
值。我不需要category
。此外,每个KV对可以具有可变数目的值的列表(但总是以相同的内部词典的year
/ code
/category
结构)。
taxonid 1986 1988 1990 1994 1996 2002 2004 2006 2008 2010 2015 2016
219 V V V V VU VU NaN NaN VU NaN VU NaN
561 R R R R EN NaN NaN LC NaN LC NaN LC
571 NaN NaN NaN NaN LR/lc NaN LC NaN LC NaN NaN LC
有没有一种生成DataFrame的方法,这样我就不必首先将所有年份声明为列?并非所有年份都在这里表示,并且每当我收到JSON对象时,都有能创建更新的df的代码会很棒。
我已经看过许多SO问题,但到目前为止,没有任何问题可以帮助破解这一问题。
如果d
是您的问题字典,则此示例:
df = pd.DataFrame( ((k, *dd.values()) for k, v in d.items() for dd in v), columns=['taxid', 'year', 'code', 'category'] )
df = pd.pivot_table(df, values='code', index='taxid', columns='year', aggfunc='first')
print(df)
印刷品:
year 1986 1988 1990 1994 1996 2002 2004 2006 2008 2010 2015 2016
taxid
219 V V V V VU VU NaN NaN VU NaN VU NaN
561 R R R R EN NaN NaN LC NaN LC NaN LC
571 NaN NaN NaN NaN LR/lc NaN LC NaN LC NaN NaN LC
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句