Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python pandas pivot_table multiple time indices

I have the following dataframe:

import pandas as pd
import datetime

df = pd.DataFrame({'T': [datetime.datetime.now(), datetime.datetime.now()], 'V': [1, 2]})

I want to pivot using both the year and month as indices, which I can do as:

df.pivot_table(index = [df['T'].dt.year, df['T'].dt.month], values = 'V')

However, since that gives me two columns named T, I am unable to set margins = True (throws the error: The name T occurs multiple times, use a level number). How can I fix this issue? Ideally I would like to name the columns manually while doing the pivot, so that I have Yearand Monthinstead of Tand T.

Any ideas?

like image 519
CHRD Avatar asked Aug 07 '26 23:08

CHRD


1 Answers

IIUC, you can use rename to rename your series,

df.pivot_table(index = [df['T'].dt.year.rename('Year'),
                        df['T'].dt.month.rename('Month')], 
                values='V',
                aggfunc='sum', 
                margins=True)

Output:

              V
Year Month     
2020 1        3
All           3
like image 126
Scott Boston Avatar answered Aug 10 '26 11:08

Scott Boston



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!