【问题标题】:Dataframe to list of dicts数据框到字典列表
【发布时间】:2020-05-15 20:44:29
【问题描述】:

我有以下数据框:

key         category    amount
2019-01     abc         123
2019-01     xyz         111
2019-02     abc         87
2019-02     xyz         34
2019-03     abc         15
2019-04     def         64

我将如何将这些数据转换为下面的字典列表。本质上,每个 dict 代表一个类别以及该类别的所有日期和相应数量:

[
  {
    "category": "abc",
    "2019-01": 123,
    "2019-02": 87,
    "2019-03": 15
  },
  {
    "category": "xyz",
    "2019-01": 111,
    "2019-02": 34
  },
  {
    "category": "def,
    "2019-04": 64
  }
]

【问题讨论】:

标签: python pandas


【解决方案1】:

在 GroupBy.apply 中使用 lambda 函数并合并 2 个字典:

f = lambda x: {**{'category': x.name}, **dict(zip(x['key'], x['amount']))}
L = df.groupby('category', sort=False).apply(f).tolist()
print (L)
[{'category': 'abc', '2019-01': 123, '2019-02': 87, '2019-03': 15}, 
 {'category': 'xyz', '2019-01': 111, '2019-02': 34},
 {'category': 'def', '2019-04': 64}]

【讨论】:

  • 甜蜜!这是一个艰难的
猜你喜欢
  • 2021-04-10
  • 1970-01-01
  • 1970-01-01
  • 2020-12-28
  • 2017-03-01
  • 1970-01-01
  • 2020-07-22
  • 1970-01-01
相关资源
最近更新 更多