gpt4 book ai didi

python - 使用 Pandas 计算客户生命周期

转载 作者:太空宇宙 更新时间:2023-11-03 13:58:34 25 4
gpt4 key购买 nike

我正在使用 python 执行同类群组分析,但在创建一个新列来总结用户在我们这里呆的总月数时遇到了问题。

我知道答案背后的数学原理,我所要做的就是:

  1. 从他们开始提供服务的年份减去他们取消我们服务的年份
  2. 将其乘以 12。
  3. 从他们开始服务的月份减去他们取消我们服务的月份。
  4. 将这两个数字相加。

在 Excel 中,它看起来像这样:

=(年(C2)-年(B2))*12+(月(C2)-月(B2))

C 是客户取消日期的时间,B 是客户开始日期的时间

问题是我对 Python 和 Pandas 非常陌生,并且在用 Python 翻译该函数时遇到了困难

到目前为止我已经尝试过:

df['Lifetime'] = df.Plan_Cancel_Date('%Y') - df.Plan_Start_Date('%Y')*12 + 
df.Plan_Cancel_Date('%m') - df.Plan_Start_Date('%m')
df.head()

它返回错误“Series”不可调用,我大致了解这意味着什么。

然后我尝试:

def LTVCalc (Plan_Start_Date, Plan_Cancel_Date):
df['Lifetime'] = df.Plan_Cancel_Date('%Y') - df.Plan_Start_Date('%Y')*12 +
df.Plan_Cancel_Date('%m') - df.Plan_Start_Date('%m')
df.head()

但这并没有将“Lifetime”列添加到 DataFrame 中。

有谁可以帮助新手吗?

最佳答案

我认为需要先转换to_datetime然后使用 dt.yeardt.month :

df = pd.DataFrame({
'Plan_Cancel_Date': ['2018-07-07','2019-03-05','2020-10-08'],
'Plan_Start_Date': ['2016-02-07','2017-01-05','2017-08-08']
})
#print (df)

#if necessary convert to datetimes
df.Plan_Start_Date = pd.to_datetime(df.Plan_Start_Date)
df.Plan_Cancel_Date = pd.to_datetime(df.Plan_Cancel_Date)

df['Lifetime'] = ((df.Plan_Cancel_Date.dt.year - df.Plan_Start_Date.dt.year)*12 +
df.Plan_Cancel_Date.dt.month - df.Plan_Start_Date.dt.month)

print (df)

Plan_Cancel_Date Plan_Start_Date Lifetime
0 2018-07-07 2016-02-07 29
1 2019-03-05 2017-01-05 26
2 2020-10-08 2017-08-08 38

关于python - 使用 Pandas 计算客户生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49421791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com