如何在python中分组,找到平均值和情节

问题描述 投票:0回答:2

这可能看起来像是一个重复的问题,但并不是因为我已经搜索和搜索,而只是得到了不适用于我的情况的复杂解决方案。我有python数据,如下所示:

id | year  | sales
1  | 2010  |200
2  | 2010  |300
3  | 2011  |500
4  | 2011  |600
5  | 2012  |300
6  | 2012  |200

我想找到不同年份的平均值,并绘制三年的图表。

我已经尝试过以下代码但不起作用:

    df.groupby(['year','sales']).count()['sales'].unstack().plot(ax=ax).show()
python python-3.x pandas matplotlib average
2个回答
2
投票

我认为需要在sales之后添加groupby,如果有必要将fill_value=0添加到unstack以替换NaNs到0

df.groupby(['year','sales'])['sales'].mean().unstack(fill_value=0).plot()

0
投票

试试这个:

df[["year","sales"]].groupby("year").mean().plot()

您可能不小心在数据集中包含了“id”。

© www.soinside.com 2019 - 2024. All rights reserved.