Pandas DataFrame 到字典列表 [英] Pandas DataFrame to List of Dictionaries

查看:48
本文介绍了Pandas DataFrame 到字典列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据帧:

<前>客户 item1 item2 item31个苹果牛奶番茄2水橙土豆3个果汁芒果片

我想把它翻译成每行的字典列表

rows = [{'客户':1,'item1': '苹果','item2': '牛奶','item3': '番茄'}, {'客户':2,'项目1':'水','item2': '橙色','item3': '土豆'}, {'客户':3,'item1': '果汁','item2': '芒果','item3': '筹码'}]

解决方案

编辑

正如 John Galt 在 他的回答 中提到的,您可能应该改用 df.to_dict('records').这比手动移调要快.

在 [20]: timeit df.T.to_dict().values()1000 个循环,最好的 3 个:每个循环 395 µs在 [21]: timeit df.to_dict('records')10000 个循环,最好的 3 个:每个循环 53 µs

<小时>

原答案

使用df.T.to_dict().values(),如下所示:

在[1]中:df出[1]:客户 item1 item2 item30 1 苹果牛奶番茄1 2水橙土豆2 3 果汁芒果片在 [2]: df.T.to_dict().values()出[2]:[{'客户':1.0,'item1':'苹果','item2':'牛奶','item3':'番茄'},{'客户':2.0,'item1':'水','item2':'橙色','item3':'土豆'},{'customer': 3.0, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}]

I have the following DataFrame:

customer    item1      item2    item3
1           apple      milk     tomato
2           water      orange   potato
3           juice      mango    chips

which I want to translate it to list of dictionaries per row

rows = [
    {
        'customer': 1,
        'item1': 'apple',
        'item2': 'milk',
        'item3': 'tomato'
    }, {
        'customer': 2,
        'item1':
        'water',
        'item2': 'orange',
        'item3': 'potato'
    }, {
        'customer': 3,
        'item1': 'juice',
        'item2': 'mango',
        'item3': 'chips'
    }
]

解决方案

Edit

As John Galt mentions in his answer , you should probably instead use df.to_dict('records'). It's faster than transposing manually.

In [20]: timeit df.T.to_dict().values()
1000 loops, best of 3: 395 µs per loop

In [21]: timeit df.to_dict('records')
10000 loops, best of 3: 53 µs per loop


Original answer

Use df.T.to_dict().values(), like below:

In [1]: df
Out[1]:
   customer  item1   item2   item3
0         1  apple    milk  tomato
1         2  water  orange  potato
2         3  juice   mango   chips

In [2]: df.T.to_dict().values()
Out[2]:
[{'customer': 1.0, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},
 {'customer': 2.0, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},
 {'customer': 3.0, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}]

这篇关于Pandas DataFrame 到字典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆