2015-04-23 366 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'}}