Search code examples
pythonpandasgroup-bycountpivot

groupby() Col A, count Col C, and count unique column B


I have a dataframe with multiple columns. I want to groupby column A (which is a person's name). Then I want to count total number of rows in column C grouped by column A. I also want to count number of unique rows in Column B grouped by column A.

Is there a way to do this in Python?


Solution

  • This:

    df.groupby('A').agg({'C':'size', 'B':'nunique'})
    

    although really, number of rows in C should just be the same with number of rows in B. This should also work

    df.groupby('A')['B'].agg(['size','nunique'])