Pandas DataFrame到词典列表

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)

  • @ GabrielL.Oliveira你可以做df.reset_index().to_dict('records') (5认同)
  • 我如何更改它以将索引值包含在结果列表的每个条目中? (2认同)
  • “records”是某种神奇的列名吗?还有其他魔法柱吗? (2认同)

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)

  • 检查下面@mirosval 和@Zero 的答案。最好的方法是使用 df.to_dict('records')` (7认同)
  • 当我使用 `df.T.to_dict().values()` 时,我也失去了排序顺序 (3认同)
  • 对于包含每个客户多行的数据帧,解决方案是什么? (2认同)

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)

我要求只选择一列并将其转换为以列名作为键的字典列表,并且在此停留了一段时间,所以我想我会分享。