python - 将按 df 分组转换为带有字典列表的字典

标签 python pandas

我有以下 df:

                  timestamp           min           max  count
0 2022-10-23 22:00:00+00:00  1.000000e+09  9.000000e+99      0
1 2022-10-23 22:00:00+00:00  1.000000e+08  1.000000e+09      2
2 2022-10-23 22:00:00+00:00  1.000000e+07  1.000000e+08     39
3 2022-10-23 22:00:00+00:00  1.000000e+06  1.000000e+07    162
4 2022-10-23 22:00:00+00:00  1.000000e+05  1.000000e+06    491
5 2022-10-23 22:00:00+00:00  1.000000e+04  1.000000e+05    960
6 2022-10-23 22:00:00+00:00  1.000000e+03  1.000000e+04    287
7 2022-10-23 22:00:00+00:00  1.000000e+02  1.000000e+03    244
8 2022-10-23 22:00:00+00:00  1.000000e+01  1.000000e+02    416
9 2022-10-23 22:00:00+00:00  0.000000e+00  1.000000e+01      1

我尝试按时间戳对其进行分组以创建以下结构:

items = {
    '2022-10-23 22:00:00+00:00': 
        [ 
            {'min': 1.000000e+09, 'max': 9.000000e+99, 'count': 0},
            {}, 
            ...
        ] 
}

我认为有一种方法可以做到类似的事情:

df.groupby('timestamp')[['max', 'min','count']].apply(lambda g: g.values.tolist()).to_dict()

但我不知道要在 lambda 函数中更改什么才能获得我需要的结果。

最佳答案

您可以使用字典理解 to_dict :

items = {k: g.to_dict('records') for k,g in
         df.set_index('timestamp').groupby('timestamp')}

输出:

{'2022-10-23 22:00:00+00:00': [{'min': 1000000000.0, 'max': 9e+99, 'count': 0},
                               {'min': 100000000.0, 'max': 1000000000.0, 'count': 2},
                               {'min': 10000000.0, 'max': 100000000.0, 'count': 39},
                               {'min': 1000000.0, 'max': 10000000.0, 'count': 162},
                               {'min': 100000.0, 'max': 1000000.0, 'count': 491},
                               {'min': 10000.0, 'max': 100000.0, 'count': 960},
                               {'min': 1000.0, 'max': 10000.0, 'count': 287},
                               {'min': 100.0, 'max': 1000.0, 'count': 244},
                               {'min': 10.0, 'max': 100.0, 'count': 416},
                               {'min': 0.0, 'max': 10.0, 'count': 1}]
}

关于python - 将按 df 分组转换为带有字典列表的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74194187/

相关文章:

python - 将 Z3Py 与 Python 3.3 结合使用

python - tensorflow 错误 : "Tensor must be from the same graph as Tensor..."

python - 查找与条件对应的下一个值

python - 使用 bokeh 或 matplotlib 的 Pandas DataFrame 分层饼图/ donut chart

python - Pandas 将列从字符串转换为 float

pandas - 将 pandas DataFrame 拆分成大致相同的 block

python - 函数不适用于文件中的空格

python - 如何通过 Python 绑定(bind)将 HtmlUnit 驱动程序与 Selenium 结合使用?

python - 创建数据框分组的切片

python - 将数据框中的非数字转换为 NaN (numpy)?