python - 使用 sns lineplot 绘制平均线
问题描述
我有一个看起来像这样的数据框:
id|date |amount
1 |02-04-18|3000
1 |05-04-19|5000
1 |10-04-19|2600
2 |10-04-19|2600
2 |11-04-19|3000
我想为每个唯一 ID 随着时间的推移花费的金额,并有一个平均趋势线。这是我拥有的代码:
import matplotlib.pyplot as plt
import pandas as pd
temp_m = df.pivot_table(index='id',columns='id',values='amount', fill_value=0)
temp_m = pd.melt(temp, id_vars=['id'])
temp_m['date'] = temp_m['date'].astype('str')
fig, ax = plt.subplots(figsize=(20,10))
for i, group in temp_m.groupby('id'):
group.plot('id', y='amount', ax=ax,legend=None)
plt.xticks(rotation = 90)
每条生产线都是一个独特的客户。
目标:我想添加另一条线,它是所有单个客户趋势的平均值。
另外,如果还有更好的方法来绘制各条线,请告诉我
解决方案
首先我们重塑数据
agg = df.set_index(['date', 'id']).unstack()
agg.columns = agg.columns.get_level_values(-1)
这使得绘图非常容易:
sns.lineplot(data=agg)
平均趋势可以通过以下方式计算
from sklearn.linear_model import LinearRegression
regress = {}
idx = agg.index.to_julian_date()[:, None]
for c in agg.columns:
regress[c] = LinearRegression().fit(idx, agg[c].fillna(0)).predict(idx)
trend = pd.Series(pd.DataFrame(regress).mean(axis=1).values, agg.index)
推荐阅读
- bash - 从 Bitbucket 获取拉取请求 ID,并传递给 Teamcity 中的 bash 脚本
- haskell - 使用 Haskell 的 Happy 解析器创建 AST 并同时管理符号表
- tkinter - Python:如何重新启动被标志停止的线程
- ruby-on-rails - Rails4生产elasticsearch错误 - 找不到geo_point,但在开发中工作
- python - Netcat 只接收来自 Scapy 和 Python 的第一个 UDP 数据包
- vba - Excel 数组过滤器
- azure - Azure 中的微服务
- c# - Windows 应用商店验证订阅服务器端
- amazon-web-services - 如何获取 AWS EMR 的实例列表?
- c++ - ubuntu上的Wt链接错误