首页 > 解决方案 > 数据框到字典收集特定值

问题描述

我有以下数据:

                       repeat  num_samples    score
dim num_centers noise                              
2   2           0.1       9.5       1000.0  0.99875
                0.2       9.5       1000.0  0.97695
                0.5       9.5       1000.0  0.95210
                1.0       9.5       1000.0  0.75535
                2.0       9.5       1000.0  0.67500
                5.0       9.5       1000.0  0.57735
                10.0      9.5       1000.0  0.56395
                100.0     9.5       1000.0  0.55320
    3           0.1       9.5       1000.0  0.99125
                0.2       9.5       1000.0  0.95110
                0.5       9.5       1000.0  0.81915
                1.0       9.5       1000.0  0.69520
                2.0       9.5       1000.0  0.51390
                5.0       9.5       1000.0  0.43085
                10.0      9.5       1000.0  0.40255
                100.0     9.5       1000.0  0.39430
3   2           0.1       9.5       1000.0  0.99990
                0.2       9.5       1000.0  0.99790
                0.5       9.5       1000.0  0.96915
                1.0       9.5       1000.0  0.86350
                2.0       9.5       1000.0  0.74360
                5.0       9.5       1000.0  0.61485
                10.0      9.5       1000.0  0.58160
                100.0     9.5       1000.0  0.57370
    3           0.1       9.5       1000.0  0.99995
                0.2       9.5       1000.0  0.98755
                0.5       9.5       1000.0  0.92930
                1.0       9.5       1000.0  0.73040
                2.0       9.5       1000.0  0.59975
                5.0       9.5       1000.0  0.46510
                10.0      9.5       1000.0  0.43385
                100.0     9.5       1000.0  0.42865

我想要一个有 4 个键的字典:

dim=2, num_centers=2
dim=2, num_centers=3
dim=3, num_centers=2
dim=3, num_centers=3

并且相应的值是具有noisescore列的 2D numpy 数组。

我怎样才能做到这一点?

标签: pandas

解决方案


对to_dict的“普通”调用不会获得所需的值,因为索引值不是唯一的。

要生成结果,请运行:

result = { key: grp.values for key, grp in df
    .reset_index(level=2).drop(columns=['repeat', 'num_samples'])
    .groupby(level=[0,1]) }

然后例如执行result[(2,2)](实际上打印这个值),你会得到:

array([[  0.1    ,   0.99875],
       [  0.2    ,   0.97695],
       [  0.5    ,   0.9521 ],
       [  1.     ,   0.75535],
       [  2.     ,   0.675  ],
       [  5.     ,   0.57735],
       [ 10.     ,   0.56395],
       [100.     ,   0.5532 ]])

或者要打印所有 4 个键和嵌入的表,请运行:

for k, v in result.items():
    print(f'{k}:\n{v!r}')

推荐阅读