我的数据包含客户购买历史以及每个订单的相应销售额。我想了解每个客户随时间的支出趋势。我考虑了对每个客户的回归,然后提取系数。这有可能以一种有效的方式处理 Pandas 吗(我在数据中有大约 1000000 笔交易)?如果是,我该怎么做?
为了更好地理解这里的数据结构。
Date Customer_ID Sales_Value
2014-07-01 1 62.946002
2014-12-01 2 62.947733
2013-05-01 3 27.328221
2015-01-01 1 30.023658
这将是交易数据的结构以及在这种情况下不需要的其他几个列。不幸的是,数据是按月计算的,因此对于日期,您只需采用以下格式:20xx-xx-01
我现在想要的是一个数组,它为我的每个客户提供基于交易数据的整个时间间隔内的 Sales_Value 的回归系数。所以基本上是这样的:
Customer_ID trend_coeff
1 -0,5
2 0
3 0
(trend_coeff 的数字当然只是为了演示而编造的)
感谢您的帮助!
最佳答案
假设您从这样的事情开始:
import pandas as pd
df = pd.DataFrame({
'a': [1, 2, 3, 1, 2, 3, 1, 2, 3],
'b': range(9),
'c': range(1, 10)})
>>> df
a b c
0 1 0 1
1 2 1 2
2 3 2 3
3 1 3 4
4 2 4 5
5 3 5 6
6 1 6 7
7 2 7 8
8 3 8 9
要对 'a'
的每个值执行 'b'
和 'c'
之间的线性回归,您可以这样做:
from sklearn import linear_model
def find_for_a(g):
p = linear_model.LinearRegression().fit(g.b.values[:, None], g.c.values)
return pd.Series({'coef': p.coef_[0], 'intercept': p.intercept_})
>>> df.groupby('a').apply(find_for_a)
coef intercept
a
1 1.0 1.0
2 1.0 1.0
3 1.0 1.0
关于python - 每个客户数据的回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36096963/