dubbbdan dubbbdan - 3 months ago 26
Python Question

Rename pandas column values from unstacked pivot table

I have pandas pivot table

merge2
that looks like:

Site TripDate Volume Early_Vol Percent_Vol
0 024l 2004-12-02 1117.134948 1117.134948 0.000000
1 024l 2005-05-07 390.980708 1117.134948 -0.650015
2 024l 2006-10-07 321.110175 1117.134948 -0.712559
3 024l 2007-10-13 527.631767 1117.134948 -0.527692
4 024l 2008-02-02 597.165065 1117.134948 -0.465449


I then subset
merge2
into
sub1


sub1 = merge2[['Site','TripDate','Percent_Vol']]
sub1= sub1.set_index(['Site','TripDate'])


sub1
looks like:

Percent_Vol
Site TripDate
024l 2004-12-02 0.000000
2005-05-07 -0.650015
2006-10-07 -0.712559
2007-10-13 -0.527692
2008-02-02 -0.465449


I then unstack
sub1
into
t
to look like:

Percent_Vol
Site 024l 029l 033l 035l_r 035l_s 041r_r
TripDate
2004-06-01 NaN NaN NaN NaN NaN NaN
2004-11-13 NaN NaN NaN NaN NaN NaN
2004-12-02 0.000000 0.000000 0.000000 0.0 0.000000 0.000000
2005-05-07 -0.650015 -0.290539 -0.300276 -1.0 -0.075511 -0.298801
2006-10-07 -0.712559 -0.769020 -0.393304 -1.0 -0.520052 -0.284686


It seems like I have two levels for my columns names in
t
(i.e.
Percent_Vol
and
Site
) and I only what
Site
. Is there a way to change the column names to just
Site
?

Answer

try this:

t.columns = t.columns.droplevel()