2015-04-23 128 views
54

我有以下数据框:熊猫数据框中列出字典

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

,我想将它转化为每行

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'}] 
+1

欢迎来到Stack Overflow!我将代码示例缩进4个空格,以便正确渲染 - 请参阅编辑帮助以获取有关格式化的更多信息。 – ByteHamster

回答

64

使用df.T.to_dict().values()字典的名单,象下面这样:

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'}] 

As John Galt在his answer中提到,你应该改为使用df.to_dict('records')。这比手动转换要快。

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 
+1

在包含每个客户多行的数据框的情况下,解决方案是什么? – JohnnySparow

+1

当我使用'df.T.to_dict()。values()'时,我也失去了排序顺序 – Hussain

+0

当打开csv文件到列表中的字典时,我用'unicodecsv.DictReader'获得了两倍的速度。 – radtek

96

使用df.to_dict('records') - 给出的输出无需外部转置。

In [2]: df.to_dict('records') 
Out[2]: 
[{'customer': 1L, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'}, 
{'customer': 2L, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'}, 
{'customer': 3L, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}] 
+0

How我是否会将其更改为将索引值包含到结果列表的每个条目中? –

+1

@ GabrielL.Oliveira你可以做df.reset_index()。to_dict('records') –

+2

这应该是接受的答案 – raffamaiden

4

进行了扩展,John Galt's答案 -

对于下面的数据帧,

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

如果你想获得的字典包括索引值的列表,你可以这样做,

df.to_dict('index') 

哪个输出字典的词典哪里ke父字典的ys是索引值。在这种特殊情况下,

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