5

I have a dataframe that has 3 columns -

enter image description here

I want to group the columns on the basis of Chopstick Length by doing something like this -

meansByCL = df_chopstick.groupby('Chopstick.Length')['Food.Pinching.Efficiency'].mean().reset_index()

but this throws an error -

AttributeError: Cannot access callable attribute 'groupby' of 'DataFrameGroupBy' objects, try using the 'apply' method

I'm not sure what this error means. Can anyone tell me what I'm doing wrong or how I can write this code differently?

4
  • What is your df_chopstick, looks like it is already a groupby object
    – Kevin Fang
    Nov 21, 2018 at 6:08
  • @KevinFang df_chopstick is the image attached. It has Food.Pinching.Efficiency for different chopstick lengths(180-240) and different individuals (1-31).
    – harry04
    Nov 21, 2018 at 6:12
  • 2
    Please double check whether it is modified elsewhere. I can reproduce this error when I call df.groupby().groupby()
    – Kevin Fang
    Nov 21, 2018 at 6:16
  • Never mind! Found what I was doing wrong. I had assigned df_chopstick = df_chopstick.groupby('Chopstick.Length') in a previous cell of Jupyter notebook.
    – harry04
    Nov 21, 2018 at 6:16

2 Answers 2

7

This happens when you are trying to groupby() a dataframe which has been already grouped before!

2
  • 1
    ...and the solution is to ungroup it with unstack() or reset_index()
    – smci
    Nov 10, 2019 at 18:44
  • unstack /reset_index when? before? after? during?
    – NL23codes
    Aug 4, 2021 at 21:26
0

For my case, I have done a groupby and it was not required. I needed to use original dataset and just Index it (not groupby it). So remove the groupby and use below to set_index.
Yeah the problem is that groupby is already done and you can't groupby it again.

df.set_index(['ColA','ColB'])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.