首页 > 解决方案 > 为熊猫数据框中的行和列设置“元名称”

问题描述

我正在尝试“漂亮”熊猫混淆矩阵,它只返回一个 2D-numpy 数组。

我想要的是添加“传奇”;一个在“Pred”列上方,一个在“Actual”行上方

像这样的东西

      
          pred
         0    1
        --------
       0|123  2
Actual  |
       1|17  200
        

(如果“实际”被旋转,那将是完美的,但这只是一件小事)。

我有以下几行用于创建没有元标题的数据框

conf_mat = confusion_matrix(y_true = y_true,y_pred = y_pred)
conf_mat = pd.DataFrame(conf_mat)
... #missing lines for the last part

我曾考虑过使用一些多索引,但我无法真正让它发挥作用

标签: pythonpandas

解决方案


利用:

conf_mat = pd.DataFrame(conf_mat)

解决方案MultiIndex

conf_mat.columns = pd.MultiIndex.from_product([['pred'], conf_mat.columns])
conf_mat.index = pd.MultiIndex.from_product([['Actual'], conf_mat.index])
print (conf_mat)
         pred     
            0    1
Actual 0  123    2
       1   17  200

或具有索引和列名称的解决方案(但某些熊猫操作应该删除此元数据):

conf_mat = conf_mat.rename_axis(index='Actual', columns='pred')
print (conf_mat)
pred      0    1
Actual          
0       123    2
1        17  200

推荐阅读