将字典列表转换为数据框

时间:2019-02-14 14:50:58

标签: python pandas list dataframe dictionary

我有大的json数据,这些数据被读入python数据帧,并每行创建一个字典列表。我需要将其转换为其他格式的数据。

数据格式如下:

{
    "data": [{
            "item": [{
                    "value": 0,
                    "type": "a"
                },
                {
                    "value": 0,
                    "type": "b"
                },
                {
                    "value": 70,
                    "type": "c"
                }
            ],
            "timestamp": "2019-01-12T04:52:06.669Z"
        },
        {
            "item": [{
                    "value": 30,
                    "type": "a"
                },
                {
                    "value": 0,
                    "type": "b"
                }
            ],
            "timestamp": "2019-01-12T04:53:06.669z"
        }
    ]
}

将数据转换为以下形式的数据框的最有效方法是什么:

时间戳----------------------------- a ------- b ------ c < / p>

2019-01-12T04:52:06.669Z ------ 0 ------- 0 ------ 70
2019-01-12T04:53:06.669Z ------ 30 ------ 0 ------ 0

到目前为止,我已经设法使用for循环来做到这一点,但是它非常低效且缓慢。到目前为止,我是这个。

with open('try.json') as f:
    data = json.load(f)

df_data = pandas.DataFrame(data['data'])
df_formatted = pandas.DataFrame(columns=['a','b','c'])

for d, timestamp in zip(df_data['item'], df_data['timestamp']):
    row = dict()
    for entry in d:
        category = entry['type']
        value = entry['value']
        row[category] = value
    row['timestamp'] = timestamp
    df_formatted = df_formatted.append(row, ignore_index=True)
df = df_formatted.fillna(0)

列表中的项目数通常为数千个。是否有任何有关如何高效执行此操作的指针或示例?

2 个答案:

答案 0 :(得分:2)

您可以通过遍历对象来解压缩嵌套的json对象。尝试

import pandas as pd
a=[
      {
       "item": [
          {
            "value": 0,
            "type": "a"
          },
          {
            "value": 0,
            "type": "b"
          },
          {
            "value": 70,
            "type": "c"
          },
        ],
        "timestamp": "2019-01-12T04:52:06.669Z"
     },
     {
        "item": [
          {
            "value": 30,
            "type": "a"
          },
          {
            "value": 0,
            "type": "b"
          }
        ],
        "timestamp": "2019-01-12T04:53:06.669z"
      }
]


cols = ['value', 'type', 'timestamp']

rows = []
for data in a:
    data_row = data['item']
    timestamp = data['timestamp']
    for row in data_row:
        row['timestamp']=timestamp
        rows.append(row)

df = pd.DataFrame(rows)
df =df.pivot_table(index='timestamp',columns=['type'],values=['value']).reset_index()
df.columns=['timestamp','a','b','c']

如果您正在寻找紧凑型解决方案,请使用json_normalize

from pandas.io.json import json_normalize
df =pd.DataFrame()
for i in range(len(a)):
    df =pd.concat([df,json_normalize(a[i]['item'])])
df =df.pivot_table(index='timestamp',columns=['type'],values=['value']).reset_index()
df.columns=['timestamp','a','b','c']

最终输出

timestamp                   a       b       c
2019-01-12T04:52:06.669Z    0.0     0.0     70.0
2019-01-12T04:53:06.669z    30.0    0.0     NaN

答案 1 :(得分:0)

您可以从json提取字典列表,并将其输入数据框。代码可能是:

df = pd.DataFrame([dict([('timestamp', d['timestamp']), ('a', 0),
                         ('b', 0), ('c', 0)]
                        + [(item['type'], item['value'])
                           for item in d['item']])for d in data['data']],
                  columns=['timestamp', 'a', 'b', 'c'])

print(df)

预期的输出:

                  timestamp   a  b   c
0  2019-01-12T04:52:06.669Z   0  0  70
1  2019-01-12T04:53:06.669z  30  0   0

这里的窍门是先建立一个具有默认值的对的列表,然后将其扩展为实际值,然后再从中构建字典。保留最后看到的值后,您实际上将构建一个包含所有相关值的字典。

columns参数仅用于确保预期的列顺序。