【问题标题】:Calculate monthly churn rate in pandas计算熊猫的月流失率
【发布时间】:2019-12-04 01:19:42
【问题描述】:

这是我的数据框中的数据示例:

test = pd.DataFrame({
    'month': [1,2,3,4,5,6,7,8,9],
    'new': [23,45,67,89,12,34,56,90,12],
    'drop': [2,4,7,9,1,4,6,9,1],
})

month   new drop
0   1   23  2
1   2   45  4
2   3   67  7
3   4   89  9
4   5   12  1
5   6   34  4
6   7   56  6
7   8   90  9
8   9   12  1

我需要计算每月的流失率。我需要对new 列中的2 行求和,然后将drop 中的值除以这个总和(以% 为单位)。

    month 1: 2*100/23
    month 2: 4*100/(23+45-2)
    month 3: 7*100/(23+45+67-2-4)

    etc.

请问有人可以提出一种优雅的方法吗?

【问题讨论】:

  • 您想每 2 行执行一次吗?还是在整个帧上累积?

标签: python-3.x pandas churn


【解决方案1】:
test = pd.DataFrame(
    {
        'month': [1, 2, 3, 4, 5, 6, 7, 8, 9],
        'new': [23, 45, 67, 89, 12, 34, 56, 90, 12],
        'drop': [2, 4, 7, 9, 1, 4, 6, 9, 1],
    }
)
df2 = test.assign(
    shifted_drop=lambda x: x['drop'].cumsum().shift(1).fillna(0.0),
    shifted_new=lambda x: x['new'].shift(1).fillna(0.0),
    churn=lambda x: x['drop'] * 100 / (x['new'] + x['shifted_new'] - x['shifted_drop'])
)[['month', 'churn']]

结果

   month     churn
0      1  8.695652
1      2  6.060606
2      3  5.426357
3      4  4.265403
4      5  0.467290
5      6  1.619433
6      7  2.006689
7      8  2.349869
8      9  0.259067

我检查前两行的结果。

【讨论】:

    【解决方案2】:

    你需要:

    test['drop'].mul(100).div((test['new'].cumsum() - test['drop'].cumsum().shift()).fillna(test['new']))
    

    输出:

    0    8.695652
    1    6.060606
    2    5.426357
    3    4.265403
    4    0.467290
    5    1.619433
    6    2.006689
    7    2.349869
    8    0.259067
    dtype: float64
    

    解释:

    (test['new'].cumsum() - test['drop'].cumsum().shift()).fillna(test['new'])
    

    提供new 的cumsum 与先前的drop cumsum 的减法。

    输出(为解释添加了cmets):

    0     23.0 # 23
    1     66.0 # 23+45-2
    2    129.0 # 23+45+67-2-4
    3    211.0
    4    214.0
    5    247.0
    6    299.0
    7    383.0
    8    386.0
    

    【讨论】:

    • 我认为我们需要 .cumsum() 和 shift 否则仅在上个月的子结构中删除数字...
    • @aviss,我不明白。这不是给你想要的输出吗?
    • 我在第 3 个月用另一行更新了我的问题。我们需要从 drop 中提取以前的值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 2017-08-11
    相关资源
    最近更新 更多