Bode
Bode

Reputation: 529

grouper with unstack ()

I have the dataframe,df

       date     name   count
 0  2017-08-07  ABC      12
 1  2017-09-08  ABC      5
 2  2017-09-22  TTT      6
 3  2017-09-23  TAC      5
 4  2017-10-09  ABC      10

It should now be:

   Index      ABC    TTT     TAC 
  August      12      0      0
  September   5       6      5
  October     10      0      0  

Then sum for each month

    index          
   August      12     
   September   16      
   October     10  

Here is the code:

df.date= pd.to_datetime(df.date)
df2 = df.groupby(pd.Grouper(key='date', freq='1M')).unstack().sum()# groupby each 1 month
df2.index = df2.index.strftime('%B')
print(df2)

I get this error:AttributeError: Cannot access callable attribute 'unstack' of 'DataFrameGroupBy' objects, try using the 'apply' method

Upvotes: 0

Views: 264

Answers (1)

Gabriel A
Gabriel A

Reputation: 1827

Unstack is used to remove a level of indices from a multi index. You applied unstack before you used an aggregation function. That's why you got the error. Even then I think there are some issues with your groupby. Does the following work for you?

df.date= pd.to_datetime(df.date)
df2 = df.groupby( [pd.Grouper(key='date', freq='1M'),"name"])["count"].sum().unstack()
df2.index = df2.index.strftime('%B')
print(df2)

Upvotes: 1

Related Questions