python - 用于忠诚度计算的线路之间的时间增量

标签 python pandas

我能够在 pandas 的帮助下制作这样的订单表: enter image description here

   identifier  gender       Date category
0           1  female 2016-11-11     Baby
1           1  female 2017-02-01     Baby
2           2  female 2016-12-19    Shave
3           2  female 2016-12-27    Shave
4           3  female 2016-11-11     Baby
5           3  female 2016-11-22     Baby
6           4    male 2016-11-11    Shave
7           4    male 2017-01-01    Shave

我需要结果作为按天计算的第一个和第二个订单的数量:

first order:
11.11.2016 3
19.12.2016 1

second orders:
22.11.2016 1
21.12.2016 1
01.01.2017 1
02.01.2017 1

third orders:

而且我还需要计算订单之间的平均时间(人)

average time between orders = ...

并评估客户的跨类别忠诚度。我觉得这些任务看起来很相似

 Loyalty cross categories:
    first order:
    Baby  2
    second order:
    Baby - 2
    third order:


    first order:
    Shave  2
    second order:
    Shave - 2
    third order:

是否可以用 pandas 进行这样的分析?

最佳答案

鉴于此数据框

   identifier  gender       Date category
0           1  female 2016-11-11     Baby
1           1  female 2017-02-01     Baby
2           2  female 2016-12-19    Shave
3           2  female 2016-12-27    Shave
4           3  female 2016-11-11     Baby
5           3  female 2016-11-22     Baby
6           4    male 2016-11-11    Shave
7           4    male 2017-01-01    Shave

您可以首先使用组功能中的系列移位

df_groups = df.groupby('identifier')
df['last_order'] = df_groups.Date.shift(1)

然后就可以得到订单之间的时间

df['Time_between_orders'] = df['last_order'] - df['Date']

然后您可以获得每个用户订单之间的平均时间,如下所示:

df_groups = df.groupby('identifier')
df_groups['Time_between_orders'].apply(lambda x: x.sum() / x.notnull().sum()).apply(lambda x: x.days)

将给出:

identifier
1          -82
2           -8
3          -11
4          -51

如果您希望跨类别进行此操作,只需将类别添加到所有组语句中即可。 df.groupby('identifier') 变为 df.groupby(['identifier', 'category'])

关于python - 用于忠诚度计算的线路之间的时间增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42509392/

相关文章:

python - 尝试传递 Python 的 C 代码,总线出现错误 IndexError : list assignment index out of range

python - Pandas Groupby 值范围

pandas - 根据列值的长度过滤数据框行

python - gsutil cp 通信问题

python - 将 (720, 720) 的 pandas DataFrame reshape 为 (518400, ) 2D 为 1D

python - 如何使用 Python 创建化学计量矩阵

Python:优化数据帧处理

python - Lambda 数据框引用另一列中的值

Python 原生协程和 send()

python - 变量赋值和修改(Python中)