简体   繁体   English

熊猫数据框分组图2

[英]Pandas dataframe groupby Plot 2

I've been going around in circles on this for a while and thought I'd post. 我已经在圈子里转了一圈了,以为我会发布。 I have a dataframe that has UserID, TimeSlot, and Count. 我有一个具有UserID,TimeSlot和Count的数据框。

I'm trying to plot 2 UserIDs (3 & 4) on separate line charts, with TimeSlot along the x-axis, and a sum of count on the Y. I've tried referring to this excellent post but can't seem to get it right for my needs. 我正在尝试在单独的折线图上绘制2个UserID(3和4),TimeSlot沿x轴,Y上的计数总和。我曾尝试引用此出色的文章,但似乎无法使它适合我的需求。

How can I fix this code? 如何解决此代码?

userList = [3,4]

    df.set_index('TimeSlot', inplace=True)
    df2 = df.groupby('UserID')
    ncols=2
    nrows = int(np.ceil(df2.ngroups/ncols))

    fig, axes = plt.subplots(nrows=4, ncols=ncols, figsize=(12,4), sharey=True)

    for (key, ax) in zip(df2.groups.keys(), axes.flatten()):
        df2.get_group(key).plot(ax=ax)

    ax.legend()
    plt.show()

Ok this was my eventual solution: 好的,这是我最终的解决方案:

df.set_index('TimeSlot', inplace=True)
userList = [1,2,3]
df2 = df.loc[df['UserID'].isin(userList)]
df2 = df2.pivot(columns='UserID', values='Count')
df2.plot()

It actually plots the lines on the same chart which I decided was fine. 它实际上在我认为还可以的同一张图表上绘制了线条。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM