python - How to Rename Multiple Columns on a Reset Index with Pandas -
i'm trying figure out if there way rename pandas columns when try reset index. see in documentation can use "name" parameter set column name of reset index if there 1 column, i'm curious if there way multiple columns.
for example:
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()
the result leaves with:
out[82]: b 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 do:
df1.set_index(['b','a']).stack().reset_index(name='my_col')
in order set name of last column i'm wondering if there way use parameter set name of 'level_2' column well.
the first thing came mind try:
df1.set_index(['b','a']).stack().reset_index(name=['my_col2','my_col'])
however, did not work looking way around. realize rename columns in next line hoping there'd cleaner way in 1 line.
thanks! sam
reset_index
not smart enough this, leverage methods rename_axis
, rename
give names index , columns/series before resetting index; once names set properly, reset_index automatically convert these names column names in result:
here rename_axis
gives names index equivalent df.index.names = ...
except in functional style; rename
gives name series object:
df1.set_index(['b','a']).stack().rename_axis(['b','a','col2']).rename('col').reset_index() # b 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 # ..
Comments
Post a Comment