简体   繁体   English

如何将pandas数据帧转换为python中的字典列表?

[英]how to convert a pandas dataframe to a list of dictionaries in python?

I have a dataframe like this:我有一个这样的数据框:

data = {'id': [1,1,2,2,2,3],
        'value': ['a','b','c','d','e','f']
}
df = pd.DataFrame (data, columns = ['id','value'])

I want to convert it to a list of dictionary like:我想将其转换为字典列表,如:

df_dict = [
{
 'id': 1,
 'value':['a','b']
},
{
'id': 2,
'value':['c','d','e']
},
{
'id': 3,
'value':['f']
}
]

And then eventually insert this list df_dict to another dictionary:然后最终将这个列表df_dict插入到另一个字典中:

{
    "products": [
        {
            "productID": 1234,
            "tag": df_dict
        }
  ]
}

We don't need to worry about how the other dictionary looks like.我们不需要担心另一本字典的样子。 We can simply use the example I gave above.我们可以简单地使用我上面给出的例子。

How do I do that?我怎么做? Many thanks!非常感谢!

You can groupby and then use to_dict to convert it to a dictionary.您可以 groupby 然后使用to_dict将其转换为字典。

>>> df.groupby(df['id'], as_index=False).agg(list).to_dict(orient="records")
[{'id': 1, 'value': ['a', 'b']}, {'id': 2, 'value': ['c', 'd', 'e']}, {'id': 3, 'value': ['f']}]

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

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