自定义格式的熊猫数据框到字典

时间:2020-01-05 23:55:38

标签: python-3.x pandas dictionary pandas-groupby custom-formatting

我正在尝试将熊猫数据框转换为字典,但是我需要一种指定的输出格式,我已经阅读并查看了许多其他答案,但是我无法解决。我的数据框看起来像:

   label   Min   Max   Prom    Desv. Est.  Cr    Tz    Cpk     Zup   Zlow    PPM    % OOS  # Datos
0  test1  1.25  1.46  1.329      0.0426  1.161 -0.023  0.697  2.090  3.077  19354      2      268
1  test2  4.80  5.50  5.110      0.1368  0.774 -1.097  0.926  2.778  4.972   2735      0      268
2  test3  2.58  2.96  2.747      0.0709  0.760 -1.029  0.973  2.918  4.977   1762      0      268

我已经尝试过此方法(以及其他选项,但这与欲望输出最相似):

dict = df.set_index('label').groupby('label').apply(lambda g: g.values.tolist()).to_dict()

我得到了:

{'test1': [[1.25, 1.46, 1.329, 0.0426, 1.161, -0.023, 0.697, 2.09, 3.077, 19354.0, 2.0, 268.0]],
 'test2': [[4.8, 5.5, 5.11, 0.1368, 0.774, -1.097, 0.926, 2.778, 4.972, 2735.0, 0.0, 268.0]],
 'test3': [[2.58, 2.96, 2.747, 0.0709, 0.76, -1.0290, 0.973, 2.918, 4.977, 1762.0, 0.0, 268.0]]}

但是我要找的东西是这样的:

{'label':'test1', 'cols':[1.25, 1.46, 1.329, 0.0426, 1.161, -0.023, 0.697, 2.09, 3.077, 19354.0, 2.0, 268.0]},
{'label':'test2', 'cols': [4.8, 5.5, 5.11, 0.1368, 0.774, -1.097, 0.926, 2.778, 4.972, 2735.0, 0.0, 268.0]}, 
{'label':'test3', 'cols': [2.58, 2.96, 2.747, 0.0709, 0.76, -1.0290, 0.973, 2.918, 4.977, 1762.0, 0.0, 268.0]}

非常感谢您的任何想法或建议。

1 个答案:

答案 0 :(得分:1)

您可以使用lambda函数构建所需的输出:

df.apply(lambda x: {'label':x.label, 'cols': x.tolist()[1:]}, axis=1).tolist()