Jonathan
Jonathan

Reputation: 11331

How can I label Pandas DataFrames columns and rows?

I'm trying to make a data frame like this:

Table

This is what I have so far:

labels = ['Rain', 'No Rain']
pd.DataFrame([[27, 63],[7, 268]], columns=labels, index=labels)

That looks like this:

enter image description here

But that doesn't create the parent categories. How can I label the columns as "Actual Weather" and the rows as "Forecast"?

Upvotes: 1

Views: 6718

Answers (2)

aldanor
aldanor

Reputation: 3481

If you mean the names of the columns and index axes, you can set .name property on those:

>>> labels = ['Rain', 'No Rain']
>>> df = pd.DataFrame([[27, 63],[7, 268]], columns=labels, index=labels)
>>> df.columns.name = 'Actual Weather'
>>> df.index.name = 'Forecast'
>>> print(df)
Actual Weather  Rain  No Rain
Forecast                     
Rain              27       63
No Rain            7      268

Upvotes: 5

EdChum
EdChum

Reputation: 394459

You want to create a multi-index for the index and the columns:

In [17]:
df = pd.DataFrame(data=[[27,63],[7,268]], columns = pd.MultiIndex.from_tuples([('Actual Weather','Rain'),('Actual Weather', 'No Rain')]),
                 index=pd.MultiIndex.from_tuples([('Forecast','Rain'),('Forecast','No Rain')]))
df

Out[17]:
                 Actual Weather        
                           Rain No Rain
Forecast Rain                27      63
         No Rain              7     268

Upvotes: 3

Related Questions