以列为字典的 Pandas 数据透视表

标签 pandas dataframe dictionary pivot

我有一个看起来像这样的数据框。只有 order 是唯一的。

vendor  order order_class    time
33       33     42        22/12/2018
33       39     189       25/12/2018
35       197    91        19/01/2019
35       22     189       18/12/2018
35       11     189       30/11/2018

如何让我的数据框看起来像这样,其中键是 order_class,值是 [(order1, time1), (order2, time2)]

vendor   dict
33       {42 : [(33, 25/12/2018)], 189 : [(39, 25/12/2018)]}
35       {91 : [(197, 19/01/2019)], 189: [(22, 18/12/2018), (11, 30/11/2018)]}

*编辑

一个订单类可以有多个(订单、时间)值,需要存储在一个列表中。

最佳答案

使用 groupbyaggzip 的替代方法:

d1 = df.groupby(['vendor', 'order_class']).agg(list).reset_index(level=1)
d2 = d1.apply(lambda s: {s['order_class']: list(zip(s['order'], s['time']))}, axis=1)
d2 = d2.groupby(level=0).agg(lambda s: {k:v for d in s for k, v in d.items()}).rename('_dict').reset_index()

 #print(d2)
vendor   dict
33       {42 : [(33, 22/12/2018)], 189 : [(39, 25/12/2018)]}
35       {91 : [(197, 19/01/2019)], 189: [(22, 18/12/2018), (11, 30/11/2018)]}

关于以列为字典的 Pandas 数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62356917/

相关文章:

dictionary - 如何使用反射反转 map

python - pandas,to_csv()转为特定格式

python - 如何使用 pandas groupby 并一起移动

python - 使用 pandas 替换正则表达式格式化字符串内的日期

python - 将 Python 列表转换为 Pandas 系列

regex - 将选项卡上的某些空格替换为-定界符

python-2.7 - Pandas DataFrame用无替换NaT

python - 单位如何统一?

c# - Dictionary<string, List<int>> 复制到另一个Dictionary

python - 从Python字典中高效地获取dstack数组