python-3.x - 如何从python中不完整的数据框创建混淆矩阵
问题描述
我有一个如下所示的数据框:
I1 I2 V
0 1 1 300
1 1 5 7
2 1 9 3
3 2 2 280
4 2 3 4
5 5 1 5
6 5 5 400
I1和I2表示索引,而V表示值。值等于 0 的索引已被省略,但我想得到一个显示所有值的混淆矩阵,即如下所示:
1 2 3 4 5 6 7 8 9
1 300 0 0 0 7 0 0 0 3
2 0 280 4 0 0 0 0 0 0
3 0 0 0 0 0 0 0 0 0
4 0 0 0 0 0 0 0 0 0
5 5 0 0 0 400 0 0 0 0
6 0 0 0 0 0 0 0 0 0
7 0 0 0 0 0 0 0 0 0
8 0 0 0 0 0 0 0 0 0
9 0 0 0 0 0 0 0 0 0
我该怎么做?
提前致谢!
解决方案
使用set_index
withunstack
进行重塑、追加缺失值添加reindex
和数据清理rename_axis
:
r = range(1, 10)
df = (df.set_index(['I1','I2'])['V']
.unstack(fill_value=0)
.reindex(index=r, columns=r, fill_value=0)
.rename_axis(None)
.rename_axis(None, axis=1))
print (df)
1 2 3 4 5 6 7 8 9
1 300 0 0 0 7 0 0 0 3
2 0 280 4 0 0 0 0 0 0
3 0 0 0 0 0 0 0 0 0
4 0 0 0 0 0 0 0 0 0
5 5 0 0 0 400 0 0 0 0
6 0 0 0 0 0 0 0 0 0
7 0 0 0 0 0 0 0 0 0
8 0 0 0 0 0 0 0 0 0
9 0 0 0 0 0 0 0 0 0
详情:
print (df.set_index(['I1','I2'])['V']
.unstack(fill_value=0))
I2 1 2 3 5 9
I1
1 300 0 0 7 3
2 0 280 4 0 0
5 5 0 0 400 0
的替代解决方案pivot
,如果所有值都是整数:
r = range(1, 10)
df = (df.pivot('I1','I2', 'V')
.fillna(0)
.astype(int)
.reindex(index=r, columns=r, fill_value=0)
.rename_axis(None)
.rename_axis(None, axis=1))
print (df)
1 2 3 4 5 6 7 8 9
1 300 0 0 0 7 0 0 0 3
2 0 280 4 0 0 0 0 0 0
3 0 0 0 0 0 0 0 0 0
4 0 0 0 0 0 0 0 0 0
5 5 0 0 0 400 0 0 0 0
6 0 0 0 0 0 0 0 0 0
7 0 0 0 0 0 0 0 0 0
8 0 0 0 0 0 0 0 0 0
9 0 0 0 0 0 0 0 0 0
推荐阅读
- python - Pandas 中 Index 和 MultiIndex 的组合(数据框中的嵌套 JSON 表示)
- c++ - 并非所有 std::packaged_tasks 在 std::async 调用中执行
- php - 如何在批量更新菜单和顶部菜单中添加自定义 woocommerce 订单状态?
- c - jsmn解析器:如何使用jsmn解析器获取json字符串中的所有键
- clickhouse - clickhouse 发生代码:999 where optimize MATERIALIZED VIEW table with ReplicatedReplacingMergeTree engine
- android - 如何使用 Builder 扩展 PlayerNotificationManager 以覆盖紧凑视图控件 Exo player 2.14
- javascript - 将 npm JS 包导出为独立脚本
- swiftui - 实现 Swift UI 选择器
- python - 对SUMO文件的误解
- streamsets - 无法将我的 Streamsets 帐户与 CDP 关联