Python熊猫:通过代理键将JSON扁平化为行的快速方法



我对pandas等包的了解相当肤浅,我一直在寻找一种将数据扁平化为行的解决方案。使用这样的dict,使用名为entry_id:的代理密钥

data = [
{
"id": 1,
"entry_id": 123,
"type": "ticker",
"value": "IBM"
},
{
"id": 2,
"entry_id": 123,
"type": "company_name",
"value": "International Business Machines"
},
{
"id": 3,
"entry_id": 123,
"type": "cusip",
"value": "01234567"
},
{
"id": 4,
"entry_id": 321,
"type": "ticker",
"value": "AAPL"
},
{
"id": 5,
"entry_id": 321,
"type": "permno",
"value": "123456"
},
{
"id": 6,
"entry_id": 321,
"type": "company_name",
"value": "Apple, Inc."
},
{
"id": 7,
"entry_id": 321,
"type": "formation_date",
"value": "1976-04-01"
}
]

我想将数据展平为按代理关键字entry_id分组的行,如下所示(空字符串或None值无关紧要(:

[
{"entry_id": 123, "ticker": "IBM", "permno": "", "company_name": "International Business Machines", "cusip": "01234567", "formation_date": ""},
{"entry_id": 321, "ticker": "AAPL", "permno": "123456", "company_name": "Apple, Inc", "cusip": "", "formation_date": "1976-04-01"}
]

我尝试过使用DataFrame的groupbyjson_normalize,但未能获得所需结果的正确魔法级别。我可以用纯Python遍历数据,但我确信这不是一个快速的解决方案。我不知道如何指定type是列,value是值,entry_id是聚合键。我对pandas以外的包裹也持开放态度。

我们可以从给定的记录列表中创建一个数据帧,然后pivot要整形的数据帧,fill用空字符串的NaN值,然后将数据帧转换为字典

df = pd.DataFrame(data)
df.pivot('entry_id', 'type', 'value').fillna('').reset_index().to_dict('r')

[{'entry_id': 123,
'company_name': 'International Business Machines',
'cusip': '01234567',
'formation_date': '',
'permno': '',
'ticker': 'IBM'},
{'entry_id': 321,
'company_name': 'Apple, Inc.',
'cusip': '',
'formation_date': '1976-04-01',
'permno': '123456',
'ticker': 'AAPL'}]

最新更新