我有一个字典,它的键是一些用户I,值是字典的列表,以一个键值对为例:
my_dict['10020'] = [{'type': 'phone', 'count': 3},
{'type': 'id_card', 'count': 1},
{'type': 'email', 'count': 2}]现在,我想创建一个DataFrame,每一行都是一个键值对,列是上述字典列表中的“类型”字段,值分别是“计数”字段,例如:
ID phone id_card email
10020 3 1 2我不知道字典里有多少种潜在的“类型”,所以不是遍历字典,把所有的类型都找出来,而是有一个方便的方法来完成工作吗?
发布于 2017-11-25 04:34:39
考虑一些变量类型的数据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。
发布于 2017-11-25 04:07:11
数据输入
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 22https://stackoverflow.com/questions/47482381
复制相似问题