Python 如何分别聚合度量和绘图组
我有以下数据集:Python 如何分别聚合度量和绘图组,python,pandas,matplotlib,seaborn,Python,Pandas,Matplotlib,Seaborn,我有以下数据集: df = pd.DataFrame() df['year'] = [2011,2011,2011,2011,2011,2011,2011,2011,2011,2011,2011,2011] df['month'] = [1,2,3,4,5,6,1,2,3,4,5,6] df['after'] = [0,0,0,1,1,1,0,0,0,1,1,1] df['campaign'] = [0,0,0,0,0,0,1,1,1,1,1,1] df['sales'] = [10000,11
df = pd.DataFrame()
df['year'] = [2011,2011,2011,2011,2011,2011,2011,2011,2011,2011,2011,2011]
df['month'] = [1,2,3,4,5,6,1,2,3,4,5,6]
df['after'] = [0,0,0,1,1,1,0,0,0,1,1,1]
df['campaign'] = [0,0,0,0,0,0,1,1,1,1,1,1]
df['sales'] = [10000,11000,12000,10500,10000,9500,7000,8000,5000,6000,6000,7000]
df['date_m'] = pd.to_datetime(df.year.astype(str) + '-' + df.month.astype(str))
我想做一个按月份和活动分组的折线图,所以我尝试了以下代码:
df['sales'].groupby(df['date_m','campaign']).mean().plot.line()
但是我收到了这个错误消息keyrerror:('date\m','campaign')
。非常感谢您的帮助。- 打印通常取决于数据框的形状
创建了一个长格式的数据帧,这对于.groupby
seaborn
创建了一个宽格式的数据框,可以轻松地与.pivot\u table
pandas.DataFrame.plot一起使用
不正确,因为df['sales'].groupby(…)
选择数据帧的一列;其他列都不可用df['sales']
将数据帧转换为长格式,这非常适合使用打印。.groupby
- 指定要通过
分隔的“活动”
参数hue
- 指定要通过
将熊猫作为pd导入
导入seaborn作为sns
将matplotlib.pyplot作为plt导入
#执行groupby并重置索引
dfg=df.groupby(['date_m','campaign'])['sales'].mean().reset_index()
#显示(dfg.head())
活动销售日期
0 2011-01-01 0 10000
1 2011-01-01 1 7000
2 2011-02-01 0 11000
3 2011-02-01 1 8000
4 2011-03-01 0 12000
#与seaborn密谋
sns.lineplot(数据=dfg,x='date\u m',y='sales',hue='campaign')
数据帧
正确地塑造数据框以进行打印,并且它有一个聚合参数。.pivot\u table
- 数据帧被塑造成宽格式
#将数据框旋转到正确的形状以便打印
dfp=df.pivot\u表(index='date\u m',columns='campaign',values='sales',aggfunc='mean')
#显示(dfp.head())
活动0 1
日期
2011-01-01 10000 7000
2011-02-01 11000 8000
2011-03-01 12000 5000
2011-04-01 10500 6000
2011-05-01 10000 6000
#绘制数据帧
dfp.plot()
直接使用matplotlib
打印
fig,ax=plt.子批次(figsize=(8,6))
对于df.campaign.unique()中的v:
#根据活动选择数据
数据=df[df.活动等式(v)]
#仅当每个日期有多个值时才需要此选项
data=data.groupby(['date\u m','campaign'])['sales'].mean().reset\u index()
绘图('date_m','sales',data=data,label=f'{v}')
plt.legend(title='campaign')
plt.show()
笔记
- 软件包版本:
- 熊猫1.2.4版
seaborn v0.11.1
matplotlib v3.3.4