熊猫-通过多个列进行分组并获得其他列的唯一计数

时间:2019-12-23 04:44:45

标签: python pandas

我有大约20列的数据框。但是,有3个特别的 在这种情况下我关注的专栏。

(日期,小时,cust_id)

现在,我要绘制如下图:-

1)“ x轴”将显示从00到23的小时数。

2)“ y轴”代表该小时内(唯一客户ID)客户的数量。

3)图表中的每一行将代表其绘制的特定日期。

我尝试了以下操作:-

fig, ax = plt.subplots()
for label, df1 in df.groupby('date'):
    df1.groupby('hour').agg(customers = ('customer_id', 'nunique')).plot(ax=ax, label=label)    

但是,上述问题很少:-

1)每个折线图的标签都显示为“ customer_id”,    已经过了。

2)此图正确吗?

1 个答案:

答案 0 :(得分:0)

尝试使用以下内容:

fig, ax = plt.subplots()
for label, df1 in df.groupby('date'):
    ax.plot(df1.groupby('hour').agg(customers = ('customer_id', 'nunique')), label=label)
ax.legend()