Dhruv Singhal
Dhruv Singhal

Reputation: 171

How to do a nested renamer in pandas in groupby function

I am trying to do like this

df_temp = df.groupby(['_SubjectId', 'QuestionTypeId'], as_index=True)['QuestionTypeId'].count()

Here Subject have 10 different values and Question type has 5 and i want to know how many Questions are there of each QuestionType and Subject, i am able to do it with it but i also want to give a name to the count returned

I am doing it like this

df_temp = df.groupby(['_SubjectId', 'QuestionTypeId'], as_index=True).agg({'QuestionTypeId': {'count': 'count'}})

But it is giving me nested renaming error , so please suggest an alternative way of achieving the result i needed, i have gone through other answers but it is not helping me

Upvotes: 1

Views: 77

Answers (1)

jezrael
jezrael

Reputation: 863291

Use names aggreagtion - it means for column QuestionTypeId use aggragation count and assign to column new:

df_temp = (df.groupby(['_SubjectId', 'QuestionTypeId'], as_index=True)
             .agg(new=('QuestionTypeId': 'count')))

Upvotes: 1

Related Questions