【问题标题】:Pivot Table in Pandas Count aggregate()Pandas 中的数据透视表 Count aggregate()
【发布时间】:2016-11-02 09:08:13
【问题描述】:

我正在尝试根据项目计算“STAGE”发生的次数,我使用 np.size 作为 aggfunc,但它返回包括项目在内的发生次数,如果预期计数为 3,则我的计数值变为两倍意味着它返回 6

我使用了下面的代码

df = pd.pivot_table(data_frame, index=['Project'],columns=['Stage'], aggfunc=np.size, fill_value=0)

【问题讨论】:

    标签: python-2.7 pandas matplotlib


    【解决方案1】:

    你需要聚合函数len:

    print (data_frame)
      Project Stage
    0      an    ip
    1     cfc    pe
    2      an    ip
    3      ap    pe
    4     cfc    pe
    5      an    ip
    6     cfc    ip
    
    df = pd.pivot_table(data_frame, 
                        index='Project',
                        columns='Stage', 
                        aggfunc=len, 
                        fill_value=0)
    print (df)
    Stage    ip  pe
    Project        
    an        3   0
    ap        0   1
    cfc       1   2
    

    size 的另一种解决方案:

    df = pd.pivot_table(data_frame, 
                        index='Project',
                        columns='Stage', 
                        aggfunc='size', 
                        fill_value=0)
    print (df)
    Stage    ip  pe
    Project        
    an        3   0
    ap        0   1
    cfc       1   2
    

    通过评论编辑:

    import matplotlib.pyplot as plt
    #all code
    
    df.plot.bar()
    plt.show()
    

    【讨论】:

    • 我们能不能把这个数据透视表直接转换成条形图,像x轴一样的项目和堆积条形的舞台
    猜你喜欢
    • 2012-10-03
    • 2021-01-17
    • 1970-01-01
    • 2023-03-23
    • 2017-05-13
    • 1970-01-01
    • 2012-05-22
    • 2018-03-31
    • 2017-01-09
    相关资源
    最近更新 更多