gpt4 book ai didi

python - Pandas - 确定 Churn 是否发生缺失年份

转载 作者:行者123 更新时间:2023-12-04 15:03:45 25 4
gpt4 key购买 nike

我有一个大型 pandas 数据框,其中包含 ID、年份、支出值和大量其他列,如下所示:

id   year    spend  .... n_columns
1 2015 321 ... ...
1 2016 342 ... ...
1 2017 843
1 2018 483
2 2015 234
2 2018 321
2 2019 232 ... ...

我正在尝试创建一个新列,该列根据下一年的值对年份进行分类。类似于:

id   year    spend   cat
1 2015 321 increase
1 2016 342 increase
1 2017 843 decrease
1 2018 483 churned #as there is no 2019 data
2 2015 234 churned #as there is no 2016 data
2 2018 321 decreased
2 2019 232 decreased
2 2020 200 nan #max data only goes up to 2020

我一直在尝试使用类似下面的方法来执行此操作,以获取年份之间的差异以确定类别:

def categorize(x):
if math.abs(x['diff']) == x['value']:
return "churned"
elif x['diff'] < 0:
return "decrease"
elif x['diff' > 0:
return "increase"
else:
return None


df = df.sort_values(['id', 'year'], ascending = True)
df['diff'] = df.groupby('id')['spend'].diff(-1)
df = df.apply(categorize, axis = 1)

但是,此方法和所有类似方法似乎都失败了,因为某些 ID 缺少年份(例如上面的 id = 2 和 year = 2015)。有没有一种简单的方法可以确保所有 id 都包含所有年份,即使这些值全部归零或清空?有没有比我现在做的更好的方法来确定一年是增加/减少/流失?

谢谢!

最佳答案

这里有一种解决方法:

扩展数据框以包含缺失的年份行;我将使用 complete来自 pyjanitor 的功能为此——它显式地暴露了缺失值:

# pip install pyjanitor

import janitor

tempo = (df.complete(columns=["id",
{"year": lambda df: np.arange(df.year.min(),
df.year.max() + 1)}]
)
.assign(temp=lambda df: df.spend.ffill(),
temp_diff=lambda df: df.temp.diff(-1)
)
)

tempo

id year spend temp temp_diff
0 1 2015 321.0 321.0 -21.0
1 1 2016 342.0 342.0 -501.0
2 1 2017 843.0 843.0 360.0
3 1 2018 483.0 483.0 0.0
4 1 2019 NaN 483.0 249.0
5 2 2015 234.0 234.0 0.0
6 2 2016 NaN 234.0 0.0
7 2 2017 NaN 234.0 -87.0
8 2 2018 321.0 321.0 89.0
9 2 2019 232.0 232.0 NaN

下一步是创造条件,结合np.select:

cond2 = (tempo.spend.shift(-1).notna()) & (tempo.temp_diff.ge(0))

cond1 = (tempo.spend.shift(-1).notna()) & (tempo.temp_diff.lt(0))

cond3 = (tempo.spend.shift(-1).isna()) & (tempo.temp_diff.eq(0))

tempo["cat"] = np.select([cond1, cond2, cond3],
["increase", "decrease", "churn"],
np.nan)


id year spend temp temp_diff cat
0 1 2015 321.0 321.0 -21.0 increase
1 1 2016 342.0 342.0 -501.0 increase
2 1 2017 843.0 843.0 360.0 decrease
3 1 2018 483.0 483.0 0.0 churn
4 1 2019 NaN 483.0 249.0 decrease
5 2 2015 234.0 234.0 0.0 churn
6 2 2016 NaN 234.0 0.0 churn
7 2 2017 NaN 234.0 -87.0 increase
8 2 2018 321.0 321.0 89.0 decrease
9 2 2019 232.0 232.0 NaN nan

过滤掉 spend 列中的空行:

   tempo.query("spend.notna()").drop(columns = ['temp_diff', 'temp'])


id year spend cat
0 1 2015 321.0 increase
1 1 2016 342.0 increase
2 1 2017 843.0 decrease
3 1 2018 483.0 churn
5 2 2015 234.0 churn
8 2 2018 321.0 decrease
9 2 2019 232.0 nan

我使用了您的原始数据框(在 2019 年停止);让我知道进展如何。

关于python - Pandas - 确定 Churn 是否发生缺失年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66522600/

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