【问题标题】:Pandas create dataframe from lists of dictionaries熊猫从字典列表创建数据框
【发布时间】:2017-11-25 12:34:39
【问题描述】:

我有一本字典,其键是一些用户 ID,值是字典列表,以一个键值对为例:

my_dict['10020'] = [{'type': 'phone', 'count': 3},
                    {'type': 'id_card', 'count': 1},
                    {'type': 'email', 'count': 2}]

现在我想创建一个 pandas DataFrame,每一行对应一个键值对,列是上面字典列表中的“类型”字段,值分别是“计数”字段,例如:

    ID    phone    id_card    email
    10020    3           1        2

我不知道字典中有多少潜在的“类型”,所以与其遍历字典并获取所有“类型”,有没有一种方便的方法来完成工作?

【问题讨论】:

  • 自己解决了。首先通过字典理解将列表转换为字典,然后 pd.DataFrame.from_dict 将完成这项工作。

标签: python pandas


【解决方案1】:

数据输入

d={'10020': [{'type': 'phone', 'count': 3},
                    {'type': 'id_card', 'count': 1},
                    {'type': 'email', 'count': 2}],
 '10021': [{'type': 'phone', 'count': 33},
 {'type': 'id_card', 'count': 11},
{'type': 'email', 'count': 22}]
}

然后我们使用pd.concate

pd.concat([pd.DataFrame(y).set_index('type').rename(columns={'count':x}).T for x,y in d.items()])


Out[480]: 
type   phone  id_card  email
10020      3        1      2
10021     33       11     22

【讨论】:

  • 我对此进行了测试,它也适用于我的问题中的输入。
  • 我打赌它应该很快。不过,我不能说。
【解决方案2】:

考虑一些具有变量类型的数据d

d = \
{
    "10021": [
        {
            "type": "fax",
            "count": 33
        },
        {
            "type": "email",
            "count": 22
        }
    ],
    "10020": [
        {
            "type": "phone",
            "count": 3
        },
        {
            "type": "id_card",
            "count": 1
        },
        {
            "type": "email",
            "count": 2
        }
    ]
}

像这样重塑您的数据:

r = [{'id' : k, 'counts' : d[k]} for k in d]    

现在,使用json_normalize + pivot

df = pd.io.json.json_normalize(r, 'counts', 'id').pivot('id', 'type', 'count')
df

type   email   fax  id_card  phone
id                                
10020    2.0   NaN      1.0    3.0
10021   22.0  33.0      NaN    NaN

这应该适用于您数据中的任何type

【讨论】:

    猜你喜欢
    • 2020-08-14
    • 2018-02-26
    • 2016-01-14
    • 1970-01-01
    • 2014-11-22
    • 1970-01-01
    • 2016-04-21
    • 1970-01-01
    相关资源
    最近更新 更多