Python Pandas : pivot table with aggfunc = count unique distinct

后端 未结 8 1752
谎友^
谎友^ 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:29

    Since none of the answers are up to date with the last version of Pandas, I am writing another solution for this problem:

    In [1]:
    import pandas as pd
    
    # Set exemple
    df2 = pd.DataFrame({'X' : ['X1', 'X1', 'X1', 'X1'], 'Y' : ['Y2','Y1','Y1','Y1'], 'Z' : ['Z3','Z1','Z1','Z2']})
    
    # Pivot
    pd.crosstab(index=df2['Y'], columns=df2['Z'], values=df2['X'], aggfunc=pd.Series.nunique)
    
    Out [1]:
    Z   Z1  Z2  Z3
    Y           
    Y1  1.0 1.0 NaN
    Y2  NaN NaN 1.0
    

提交回复
热议问题