simple pivot table of pandas dataframe

前端 未结 1 1833
梦谈多话
梦谈多话 2020-12-20 17:42

I\'m trying to do a seemingly very simple task. Given a dataframe:

daf = pd.DataFrame({\'co\':[\'g\',\'r\',\'b\',\'r\',\'g\',\'r\',\'b\',\'g\'], \'sh\':[

相关标签:
1条回答
  • 2020-12-20 18:10

    It can be done more simply using pandas.crosstab:

    >>> pandas.crosstab(d.co, d.sh)
    sh  c  r  s
    co         
    b   1  1  0
    g   1  2  0
    r   0  1  2
    

    You can do it with pivot_table, but it will give you NaN instead of 0 for missing combos. You need to specify len as the aggregating function:

    >>> d.pivot_table(index='co', columns='sh', aggfunc=len)
    sh   c  r   s
    co           
    b    1  1 NaN
    g    1  2 NaN
    r  NaN  1   2
    
    0 讨论(0)
提交回复
热议问题