How to Rename Multiple Columns on a Reset Index with Pandas
reset_index
is not smart enough to do this, but we could leverage methods rename_axis
and rename
to give names to the index and columns/series before resetting the index; once the names are set up properly, reset_index will automatically convert these names to the column names in the result:
Here rename_axis
gives names to index which is somewhat equivalent to df.index.names = ...
except in a functional style; rename
gives name to the Series object:
df1.set_index(['B','A']).stack().rename_axis(['B','A','col2']).rename('col').reset_index()# B A col2 col#0 b1 a1 D1 1#1 b1 a1 D2 0#2 b1 a1 D3 0#3 b2 a1 D1 0#4 b2 a1 D2 1# ..
There are a lot of options, I believe but set_axis()
function will do the job if you have just several columns.
df1.set_index(['B','A']).stack().reset_index().set_axis(['my_col2','my_col'], axis=1)