Haytham
Haytham

Reputation: 502

How to return index after groupby condition it meet?

I have a large df.pandas and I wanted to make a function to groupby a column and count uniqe values in another column and then return the index of the max count value, like so:

def groupby_fun():
    x = df.groupby(by=df['Column1'])['Column2'].nunique()
    return [x.max()].index[0]
groupby_fun()

I get this error:

'builtin_function_or_method' object is not subscriptable

what am I doing wrong, please?

Upvotes: 1

Views: 831

Answers (1)

Haytham
Haytham

Reputation: 502

Adding .idxmax() as Nickil Maveli suggested worked:

df.groupby('Column1')['Column2'].nunique().idxmax()

Upvotes: 1

Related Questions