[英]Pandas DataFrame to List of Dictionaries
我有以下數據幀:
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'
}
]
使用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'}]
正如 John Galt 在他的回答中提到的,您可能應該改用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
使用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'}]
作為約翰高爾特答案的延伸 -
對於以下數據幀,
customer item1 item2 item3
0 1 apple milk tomato
1 2 water orange potato
2 3 juice mango chips
如果您想獲得包含索引值的字典列表,您可以執行以下操作,
df.to_dict('index')
它輸出一個字典字典,其中父字典的鍵是索引值。 在這種特殊情況下,
{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'}}
如果您只對選擇一列感興趣,這將起作用。
df[["item1"]].to_dict("records")
下面將不起作用,並且產生一個類型錯誤:不支持的類型。 我相信這是因為它試圖將系列轉換為字典,而不是將數據幀轉換為字典。
df["item1"].to_dict("records")
我要求只選擇一列並將其轉換為以列名作為鍵的字典列表,並在此停留了一段時間,所以我想我會分享。
您也可以遍歷行:
rows = []
for index, row in df[['customer', 'item1', 'item2', 'item3']].iterrows():
rows.append({
'customer': row['customer'],
'item1': row['item1'],
'item2': row['item2'],
'item3': row['item3'],
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.