pandas - 数据框到字典收集特定值
问题描述
我有以下数据:
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
并且相应的值是具有noise
和score
列的 2D numpy 数组。
我怎样才能做到这一点?
解决方案
对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}')
推荐阅读
- html - 有没有办法让平行四边形 div 适合整个页面宽度和同一行?
- excel - 以特定方式反转文本
- c++ - 基类不可访问错误,为什么私有继承会这样做?
- javascript - JavaScript中的字符串到整数对象散列
- node.js - 如何使用 node.js 在 Redis 中同步 mongoDB 数据库的更改
- mysql - 如何将ip地址插入mysql
- html-framework-7 - Framework7 已经初始化(React)
- qt5 - bitbake:如何恢复编译
- python-3.x - 如何知道用户是否在 wxPyhton 中更改了 AuiNotebook 的选项卡顺序?
- php - 带有准备好的语句的 mysqli_stmt_num_rows 不返回行数