首页 > 解决方案 > 如何从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

I1I2表示索引,而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

我该怎么做?

提前致谢!

标签: python-3.xpandasconfusion-matrix

解决方案


使用set_indexwithunstack进行重塑、追加缺失值添加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

推荐阅读