I am trying to figure out if there is a way to rename Pandas columns when trying to reset the index. I see in the documentation that you can use the "name" parameter to set the index column name to reset if there is only one column, but I'm curious if there is a way to do this for multiple columns.
For instance:
df1 = pd.DataFrame({ 'A' : ['a1', 'a1', 'a2', 'a3'], 'B' : ['b1', 'b2', 'b3', 'b4'], 'D1' : [1,0,0,0], 'D2' : [0,1,1,0], 'D3' : [0,0,1,1], }) df1.set_index(['B','A']).stack().reset_index()
As a result, you will receive:
Out[82]: BA level_2 0 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
You can do:
df1.set_index(['B','A']).stack().reset_index(name='my_col')
To set the name of the last column, but I wonder if there is a way to use this parameter to set the column name to "level_2".
The first thing that occurred to me was to try:
df1.set_index(['B','A']).stack().reset_index(name=['my_col2','my_col'])
However, this did not work, so you need to look for another way. I understand that I could always just rename the columns in the next row, but I hoped there would be a cleaner way to do this in one row.
Thanks! Sam