简体   繁体   English

将嵌套字典列表转换为 pandas DataFrame

[英]Convert list of nested dictionaries to pandas DataFrame

I have a data that is converted to a list.我有一个转换为列表的数据。 How do I convert this to a DataFrame such that each row in that list becomes a column in the DataFrame ?如何将其转换为DataFrame以便该列表中的每一行成为DataFrame中的一列?

[{'date': '2019-01-01',
  'stats': [{'metrics': {'comp_1': 149, 
                         'comp_2': 276}}]},
 {'date': '2019-01-02',
  'stats': [{'metrics': {'comp_1': 232, 
                         'comp_2': 842}}]}]

I tried to do pd.DataFrame(c) where c was the variable holding the list but I saw all components of each date was stored in a single row我试图做pd.DataFrame(c)其中c是保存列表的变量,但我看到每个日期的所有组件都存储在一行中

Expected output:预期 output:

date, comp_1, comp_2
2019-01-01,149,276
2019-01-02,232,842

Use json.json_normalize first:首先使用json.json_normalize

a = [{'date': '2019-01-01',
'stats': [{'metrics': {'comp_1': 149,
 'comp_2': 276}}]},
{'date': '2019-01-02',
'stats': [{'metrics': {'comp_1': 232,
 'comp_2': 842}}]}]

from pandas.io.json import json_normalize

df = json_normalize(a,'stats', ['date'])
print (df)
   metrics.comp_1  metrics.comp_2        date
0             149             276  2019-01-01
1             232             842  2019-01-02

Last convert columns names to list and reorder by subset:最后将列名转换为列表并按子集重新排序:

df = df[df.columns[-1:].tolist() + df.columns[:-1].tolist()]
print (df)
         date  metrics.comp_1  metrics.comp_2
0  2019-01-01             149             276
1  2019-01-02             232             842

EDIT:编辑:

Solution with loop:带循环的解决方案:

out = []
for x in a:
    for k, v in x.items():
        for z in v:
            if isinstance(z, dict):
                d = z['metrics']
                d['year'] = x['date']
                out.append(d)

df = pd.DataFrame(out)   
print (df)
   comp_1  comp_2        year
0     149     276  2019-01-01
1     232     842  2019-01-02

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM