How to Rename Multiple Columns on a Reset Index with Pandas

青春壹個敷衍的年華 提交于 2019-12-05 05:01:56

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
# ..
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!