我有一个包含二进制列的dataframe,它表示非活动客户(0 =活动客户,1=非活动客户),如下所示:
month customer_id inactive
2020-01 customer_1 0
2020-01 customer_2 0
2020-01 customer_3 0
2020-01 customer_3 0
2020-02 customer_1 0
2020-02 customer_1 0
2020-02 customer_2 0
2020-02 customer_2 0
2020-03 customer_2 1
2020-03 customer_3 1
2020-03 customer_4 0
2020-03 customer_4 0
2020-04 customer_1 0
2020-04 customer_1 1
2020-04 customer_4 0
2020-04 customer_5 0
为了更好地查看活跃客户总数,我想计算每月唯一客户的累计数量,并减去已变为非活跃客户的数量。我正在寻找如下所示的输出:
month cum_count_unique_customers
2020-01 3
2020-02 3
2020-03 2
2020-04 3
有没有办法用Pandas得到这个结果呢?
谢谢你的帮助!
发布于 2021-07-27 14:59:53
也许你可以试试这个:
import pandas as pd
df = pd.DataFrame({'month':['2020-01','2020-01','2020-01','2020-02','2020-02'],
'customer_id':['customer_1','customer_2','customer_1',
'customer_1','customer_2']})
df[df.inactive == 0].groupby('month')['customer_id'].nunique()
首先按月份对数据帧进行分组,然后计算唯一客户ids的数量
发布于 2021-07-27 15:07:20
这不是最优雅的解决方案,但如果您熟悉SQL,它可能会有所帮助:
df = df[df['inactive']!=0]
df = df[['month', 'customer_id']].groupby(['month']).count()
df.rename(columns={"customer_id": "cum_count_unique_customers"})
其中df
是一个熊猫数据帧。
https://stackoverflow.com/questions/68547057
复制