user2100039
user2100039

Reputation: 1366

Panda Move Same Index Names to Unique Column Names

I have a pandas df "lty" of shape 366,1 that looks like this below with the first "time" col is a month or Jan in this case, with the second "time" column is a day of the month. This is the result of

lty = ylt.groupby([ylt.index.month, ylt.index.day]).mean()

I need to reset the index possibly or get the columns to be renamed like this below so that "lty" has shape 366,3:

             LT Mean
time time           
1    1     11.263604
     2     11.971495
     3     11.989080
     4     12.558736
     5     11.850899

             
month day  LT Mean        
1    1     11.263604
     2     11.971495
     3     11.989080
     4     12.558736
     5     11.850899

I have tried to reset the index and i get this error:

lty.reset_index()

ValueError: cannot insert time, already exists

Thank you since I am still learning how to manipulate columns, indexing.

Upvotes: 1

Views: 102

Answers (1)

ALollz
ALollz

Reputation: 59579

When you groupby, rename grouping Index attributes that way they don't collide after the aggregation:

lty = (ylt.groupby([ylt.index.month.rename('month'), ylt.index.day.rename('day')])
          .mean().reset_index())

#month day   LT Mean          
#1     1     11.263604
#1     2     11.971495
#1     3     11.989080
#1     4     12.558736
#1     5     11.850899

Upvotes: 1

Related Questions