Reputation: 969
In a personal project I played with a dataframe and had something like this
In[1] :
from random import random
companies = ['Google', 'Apple', 'Nike', 'Microsoft']
Years = [2020, 2019, 2018]
df = pd.DataFrame(columns=['Company', 'Year', 'Money'])
iterator = 0
for company in companies:
for year in Years:
df.loc[iterator] = [company, year, random()]
iterator += 1
df.set_index('Year').pivot(columns='Company', values='Money')
Out[1]:
Company Apple Google Microsoft Nike
Year
2018 0.290925 0.568462 0.459147 0.755947
2019 0.919250 0.529112 0.881319 0.700846
2020 0.064253 0.742629 0.232048 0.522739
I would like to get ride of Company
& Year
so my output becomes
Out[2]:
Apple Google Microsoft Nike
2018 0.290925 0.568462 0.459147 0.755947
2019 0.919250 0.529112 0.881319 0.700846
2020 0.064253 0.742629 0.232048 0.522739
I know that the Raw Index name can be removed like this:
del df.index.name
But how to remove the columns index name ?
Upvotes: 1
Views: 126
Reputation: 153500
You can do this using:
del df.columns.name
or both at the same time using
df.rename_axis(index=None, columns=None)
So, at then end of your pivot statement, chain the rename_axis
method like this:
df = df.set_index('Year').pivot(columns='Company', values='Money')\
.rename_axis(index=None, columns=None)
Output:
Apple Google Microsoft Nike
2018 0.491759 0.102509 0.799196 0.603748
2019 0.640801 0.966476 0.401801 0.928443
2020 0.678182 0.373457 0.524619 0.389381
Upvotes: 1
Reputation: 3224
Just rename columns and index to None
df.columns.name, df.index.name = None, None
Result
Apple Google Microsoft Nike
2018 0.385702 0.402060 0.649404 0.640924
2019 0.999002 0.869702 0.129008 0.082098
2020 0.993765 0.402157 0.902664 0.774389
Upvotes: 1