Moh*_*him 125 python dictionary list dataframe pandas
我有以下DataFrame:
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'}]
Run Code Online (Sandbox Code Playgroud)
Zer*_*ero 180
使用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'}]
Run Code Online (Sandbox Code Playgroud)
Com*_*low 139
正如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
Run Code Online (Sandbox Code Playgroud)
使用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'}]
Run Code Online (Sandbox Code Playgroud)
Hos*_*dir 12
作为John Galt答案的延伸-
对于以下DataFrame,
customer item1 item2 item3
0 1 apple milk tomato
1 2 water orange potato
2 3 juice mango chips
Run Code Online (Sandbox Code Playgroud)
如果你想获得一个包含索引值的字典列表,你可以这样做,
df.to_dict('index')
Run Code Online (Sandbox Code Playgroud)
其中输出字典字典,其中父字典的键是索引值.在这种特殊情况下,
{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'}}
Run Code Online (Sandbox Code Playgroud)
小智 5
如果您只对选择一列感兴趣,这将起作用。
df[["item1"]].to_dict("records")
Run Code Online (Sandbox Code Playgroud)
下面将不工作,并产生一个类型错误:不支持的类型。我相信这是因为它试图将系列转换为字典,而不是将数据帧转换为字典。
df["item1"].to_dict("records")
Run Code Online (Sandbox Code Playgroud)
我要求只选择一列并将其转换为以列名作为键的字典列表,并且在此停留了一段时间,所以我想我会分享。