我对 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 的 groupby
和 json_normalize
,但一直无法获得所需结果的正确魔法水平。我可以用纯 Python 处理数据,但我确信这不是一个快速的解决方案。我不确定如何指定 type
是列,value
是值,而 entry_id
是聚合键。我也接受 pandas
以外的包裹。
答案 0 :(得分:11)
我们可以从给定的记录列表中创建一个数据框,然后 pivot
要重塑的数据框,fill
带有空字符串的 NaN
值,然后将旋转的框转换为字典< /p>
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'}]