代码之家  ›  专栏  ›  技术社区  ›  shamalaia

熊猫分组通过绘制每组

  •  2
  • shamalaia  · 技术社区  · 7 年前

    我有一些数据,我想从中提取收入的时间序列(和 Dollars 在不同的日期 Day 在不同的地点 Where )对于不同的产品( x y )

    import pandas as pd
    
    #Create data
    data = {'Day': [1,1,2,2,3,3],
            'Where': ['A','B','A','B','B','B'],
            'What': ['x','y','x','x','x','y'],
            'Dollars': [100,200,100,100,100,200]}
    
    index = range(len(data['Day']))
    
    columns = ['Day','Where','What','Dollars']
    
    
    df = pd.DataFrame(data,  index=index, columns=columns)
    df
    

    ddd

    为此,我将数据分组 What 求和 美元 :

    #Group by Day and What and sum Dollars (for each Where)
    print(df.groupby(['Day', 'What'])['Dollars'].sum())
    

    ccc

    现在,我想为 X Y 像这样:

    iii

    我尝试了以下方法,但显然不起作用:

    items = df.What.unique()
    
    ax = plt.figure()
    for item in items:
        df_tmp = df[['Day']][df.What == item]
        plt.plot(df_tmp['Day'],df_tmp,'.-',label=item)
    

    fff

    有人能帮我找到正确的方向吗? 有没有更快的方法达到正确的结果?

    1 回复  |  直到 7 年前
        1
  •  2
  •   cs95 abhishek58g    7 年前

    IIUC unstack 和情节:

    (df.groupby(['Day', 'What'])['Dollars']
       .sum()
       .unstack('What', fill_value=0)
       .plot())
    plt.show()
    

    enter image description here