Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: datetime64 type does not support sum operations

TypeError Traceback (most recent call last) Cell In[31], line 1 ----> 1 df_sale.pivot_table(index='Gender', aggfunc='sum')

Attached is my data frame generated from the google excel sheet.enter image description here

TypeError: datetime64 type does not support sum operations

I was trying to create a pivot table using the pivot_table() method. Then i try displaying the sum of all the numerical columns. But it is throwing and error because of the Date and Time columns (which i bet are being considered as numerical).What is the best solution for this issue?

the command i ran in my jupyter notebook : df_sale.pivot_table(index='Gender', aggfunc='sum')

like image 728
blessed son Avatar asked Oct 22 '25 21:10

blessed son


1 Answers

Simpliest here is aggregate sum with numeric_only=True parameter:

rng = pd.date_range('2017-04-03', periods=10)
df_sale = pd.DataFrame({'Date': rng, 'a': range(10), 'Gender':list('fffffmmmmm')})  

df = df_sale.groupby('Gender').sum(numeric_only=True)
print (df)
         a
Gender    
f       10
m       35

Your solution working if select numeric columns by DataFrame.select_dtypes with convert Gender column to index by DataFrame.set_index, because Gender column is non numeric:

df = (df_sale.set_index('Gender')
             .select_dtypes(np.number)
             .pivot_table(index='Gender', aggfunc='sum'))
print (df)
         a
Gender    
f       10
m       35
like image 136
jezrael Avatar answered Oct 27 '25 05:10

jezrael



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!