daveskis
daveskis

Reputation: 153

Python column header from pivot table

I've got the below dataframe that was generated from through pivot_table:

                cost    value
action           BUY     SELL
date                         
2001-04-27  79593.61      0.0
2001-05-04  29846.89  29132.6
2001-05-11  39786.30  40896.9
2001-05-18  29846.89  29550.5
2001-05-25  29844.71  29044.7
...              ...      ...
2020-08-28   9944.97   9955.3
2020-09-04   9944.04   9719.0
2020-09-11   9932.20  17751.5
2020-09-18  29849.57  29483.3
2020-09-25      0.00  86172.4

However I now just want three basic column headers date,cost,value. But when I try to assign columns names through cost_df = cost_df.columns['cost','value'], I get an Index Error.

Upvotes: 1

Views: 747

Answers (1)

jcaliz
jcaliz

Reputation: 4021

Your column axis is multi-index. If you need to select data by using the first level of the multi-index and remove the second level, just re-assing the columns:

cost_df.columns = ['cost', 'value']
cost_df[['cost', 'value']].head()

#                cost    value
# date                         
# 2001-04-27  79593.61      0.0
# 2001-05-04  29846.89  29132.6
# 2001-05-11  39786.30  40896.9
# 2001-05-18  29846.89  29550.5
# 2001-05-25  29844.71  29044.7

Upvotes: 1

Related Questions