CutePoison
CutePoison

Reputation: 5365

Set "meta name" for rows and columns in pandas dataframe

I am trying to "prettyfi" pandas confusion matrix which just returns a 2D-numpy array.

What I want to, is to add "legends"; one above the columns saying "Pred" and one for the rows saying "Actual"

something like this

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

(would be perfect if "actual" was rotated but thats just a minor thing).

I have the following lines for creating the dataframe w/o the meta-headers

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

and I have thought about using some multiindex but I cannot really make it work

Upvotes: 0

Views: 47

Answers (1)

jezrael
jezrael

Reputation: 863166

Use:

conf_mat = pd.DataFrame(conf_mat)

Solution with 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

Or solution with index and columns names (but some pandas operation should remeved this meta data):

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

Upvotes: 1

Related Questions