Pandas DataFrame到字典列表

fwzugrvs  于 2023-11-15  发布在  其他
关注(0)|答案(6)|浏览(220)

我有以下DataFrame:

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

字符串
我想把它转换成每行的字典列表

  1. rows = [
  2. {
  3. 'customer': 1,
  4. 'item1': 'apple',
  5. 'item2': 'milk',
  6. 'item3': 'tomato'
  7. }, {
  8. 'customer': 2,
  9. 'item1':
  10. 'water',
  11. 'item2': 'orange',
  12. 'item3': 'potato'
  13. }, {
  14. 'customer': 3,
  15. 'item1': 'juice',
  16. 'item2': 'mango',
  17. 'item3': 'chips'
  18. }
  19. ]

dfty9e19

dfty9e191#

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

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

字符串

ujv3wf0j

ujv3wf0j2#

使用df.T.to_dict().values(),如下所示:

  1. In [1]: df
  2. Out[1]:
  3. customer item1 item2 item3
  4. 0 1 apple milk tomato
  5. 1 2 water orange potato
  6. 2 3 juice mango chips
  7. In [2]: df.T.to_dict().values()
  8. Out[2]:
  9. [{'customer': 1.0, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},
  10. {'customer': 2.0, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},
  11. {'customer': 3.0, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}]

字符串

rmbxnbpk

rmbxnbpk3#

作为John Galt's答案的扩展-
对于以下DataFrame,

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

字符串
如果你想得到一个包含索引值的字典列表,你可以这样做,

  1. df.to_dict('index')


它输出字典的字典,其中父字典的键是索引值。在这种特定情况下,

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

展开查看全部
aemubtdh

aemubtdh4#

如果您只想选择一个列,这将起作用。

  1. df[["item1"]].to_dict("records")

字符串
下面将NOT工作,并产生一个TypeError:unsupported type:.我相信这是因为它试图将一个系列转换为一个dict,而不是将一个 Dataframe 转换为一个dict。

  1. df["item1"].to_dict("records")


我有一个要求,只选择一个列,并将其转换为一个列表的字典与列名作为关键字,并坚持在这一点,所以我想我会分享。

cuxqih21

cuxqih215#

你也可以选择行:

  1. rows = []
  2. for index, row in df[['customer', 'item1', 'item2', 'item3']].iterrows():
  3. rows.append({
  4. 'customer': row['customer'],
  5. 'item1': row['item1'],
  6. 'item2': row['item2'],
  7. 'item3': row['item3'],
  8. })

字符串

dbf7pr2w

dbf7pr2w6#

您可以用途:

  1. my_records = df.to_dict(orient='records')
  2. print(my_records)
  3. [{'customer': 1, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},
  4. {'customer': 2, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},
  5. {'customer': 3, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}]

字符串

相关问题