Reputation: 11331
I'm trying to make a data frame like this:
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:
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
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
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