Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas pivot_table keep index

i have a dataframe :

import pandas as pd

data = {'day_bucket': ['2011-01-21', '2011-01-22', '2011-01-23', '2011-01-24'], 'label': ['birds', 'birds', 'birds', 'birds'], 'numeric_value': [4, 0, 7, 3]}

df = pd.DataFrame(data)

   day_bucket  label  numeric_value
0  2011-01-21  birds              4
1  2011-01-22  birds              0
2  2011-01-23  birds              7
3  2011-01-24  birds              3

I want to pivot this dataframe so that i have a column birds with the values below it.

pd.pivot_table(df, values='numeric_value', index='day_bucket',columns='label')  

gives:

label       birds
day_bucket             
2011-01-21  4
2011-01-22  0
2011-01-23  7
2011-01-24  3

what should i do the keep the index? The result will look like:

    day_bucket birds    
0   2011-01-21  4
1   2011-01-22  0
2   2011-01-23  7
3   2011-01-24  3 
like image 505
Vincent Claes Avatar asked Aug 02 '16 20:08

Vincent Claes


People also ask

How do I reset the index after pivot pandas?

How to Reset an Index in Pandas. Pandas comes built in with a handy dataframe method, the . reset_index() method, that lets you, well, reset a Pandas dataframe's index.

How do I make a DataFrame index a column?

In order to set index to column in pandas DataFrame use reset_index() method. By using this you can also set single, multiple indexes to a column. If you are not aware by default, pandas adds an index to each row of the pandas DataFrame.

How do I pivot multiple columns in pandas?

Using the Pandas pivot_table() function we can reshape the DataFrame on multiple columns in the form of an Excel pivot table. To group the data in a pivot table we will need to pass a DataFrame into this function and the multiple columns you wanted to group as an index.


2 Answers

set_index with append

df.set_index(['day_bucket', 'label'], append=True) \
  .rename_axis([None, None, None]).squeeze().unstack()


              birds
0 2011-01-21      4
1 2011-01-22      0
2 2011-01-23      7
3 2011-01-24      3
like image 92
piRSquared Avatar answered Oct 10 '22 22:10

piRSquared


In the meantime, I also came up with a result

pd.pivot_table(df, values='numeric_value', 
                   index=[df.index.values,'day_bucket'],
                   ,columns='label').reset_index('day_bucket')

label  day_bucket  mortality_birds
0      2011-01-21                4
1      2011-01-22                0
2      2011-01-23                7
3      2011-01-24                3
like image 26
Vincent Claes Avatar answered Oct 11 '22 00:10

Vincent Claes