pandas reset index after performing groupby and retain selective columns

前端 未结 2 325
逝去的感伤
逝去的感伤 2021-01-20 20:36

I want to take a pandas dataframe, do a count of unique elements by a column and retain 2 of the columns. But I get a multi-index dataframe after groupby which I am unable t

2条回答
  •  伪装坚强ぢ
    2021-01-20 21:27

    Use SeriesGroupBy.nunique and filter columns in list after groupby:

    df2 = df.groupby('Ticker')['Date_1','Count','ID'].nunique().reset_index()
    print(df2)
      Ticker  Date_1  Count  ID
    0     AA       1      1   1
    1     BB       2      2   2
    2     CC       2      2   2
    3     DD       1      1   1
    

提交回复
热议问题