我有以下数据框:
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'}]
使用^{} ——提供输出而不必外部转置。
编辑
正如John Galt在his answer 中提到的,您可能应该改为使用
df.to_dict('records')
。它比手动转置要快。原始答案
使用
df.T.to_dict().values()
,如下所示:作为John Galt's答案的扩展-
对于以下数据帧
如果你想得到一个包含索引值的字典列表,你可以这样做
它输出字典,其中父字典的键是索引值。在这种情况下
相关问题 更多 >
编程相关推荐