0

I have a dataframe :

ID CATEGORY AMOUNT
1   T1       1000
2   T2       1500
3   T3       2000
4   T4       3000
5   T1       2000
6   T2       2500
7   T3       7000
8   T4       4000
9   T1       1000
10   T2      1500
11   T3      2000
12   T4      3000 

I want to groupby category and then get the mode of each category:

T1 1000
T2 1500

All the way to T4. When I run the below python code I get an error:

df['AMOUNT'].groupby(df['CATEGORY']).mode()

I get the below error

AttributeError: Cannot access callable attribute 'mode' of 'SeriesGroupBy' objects, try using the 'apply' method

Sociopath
  • 13,068
  • 19
  • 47
  • 75

3 Answers3

0

You need to group full data frame and then apply mode function:

df.groupby(['CATEGORY'])['AMOUNT'].apply(lambda x: x.mode()[x.mode().index[-1]])
Lev Zakharov
  • 2,409
  • 1
  • 10
  • 24
0

I think you need:

df.groupby('CATEGORY')['AMOUNT'].agg(lambda x:x.value_counts().index[0])
Sociopath
  • 13,068
  • 19
  • 47
  • 75
0

Try using mode function from statistics module:

from statistics import mode
result = df.groupby('CATEGORY')['AMOUNT'].aggregate(lambda x : mode(x))
print(result)

#    CATEGORY
# T1    1000
# T2    1500
# T3    2000
# T4    3000
RobJan
  • 1,351
  • 1
  • 14
  • 18