Python Pandas : pivot table with aggfunc = count unique distinct

后端 未结 8 1745
谎友^
谎友^ 2020-12-07 13:02
df2 = pd.DataFrame({\'X\' : [\'X1\', \'X1\', \'X1\', \'X1\'], \'Y\' : [\'Y2\',\'Y1\',\'Y1\',\'Y1\'], \'Z\' : [\'Z3\',\'Z1\',\'Z1\',\'Z2\']})

    X   Y   Z
0  X1  Y2         


        
8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-07 13:42

    aggfunc=pd.Series.nunique provides distinct count.

    Full Code:

    df2.pivot_table(values='X', rows='Y', cols='Z', 
                             aggfunc=pd.Series.nunique)
    

    Credit to @hume for this solution (see comment under the accepted answer). Adding as an answer here for better discoverability.

提交回复
热议问题