根据列值切片Pandas df

时间:2019-02-25 20:23:10

标签: python pandas

您将如何执行以下操作?

  • 对于流失率为1的客户,请根据他们离开的月份得出最近3次购买的平均值。例如。 Churn_Month = 3,然后平均最近3次购买:3月,2月和1月(如果有)。有时会购买2或1。

  • 对于流失率为0的客户,取其最近3次购买(如果有)的平均值,有时是2或1次购买。

并将其全部放入一个pandas Dataframe中。请参见预期的产量

可用信息

df1::您会在这里找到带有客户ID,日期,purchase1和Purchase2的交易。

    ID  DATE        P1  P2
0   1   2003-04-01  449 55
1   4   2003-02-01  406 213
2   3   2003-11-01  332 372
3   1   2003-03-01  61  336
4   3   2003-10-01  428 247
5   3   2003-12-01  335 339
6   3   2003-09-01  367 41
7   2   2003-01-01  11  270
8   1   2003-01-01  55  102
9   2   2003-02-01  244 500
10  1   2003-02-01  456 272
11  5   2003-03-01  240 180
12  4   2002-12-01  156 152
13  5   2003-01-01  144 185
14  4   2003-01-01  246 428
15  1   2003-05-01  492 97
16  5   2003-02-01  371 66
17  5   2003-04-01  246 428
18  5   2003-05-01  406 213

df2::您会在这里找到客户ID,无论他们是否离开公司以及他们离开的月份(例如3.0 = 3月)

    ID  Churn   Churn_Month
0   1       1   3.0
1   2       0   0.0
2   3       1   12.0
3   4       0   0.0
4   5       1   4.0

预期输出:

P1和P2的ID平均值,与df2信息合并。 ID将是新索引。

ID  P1      P2      Churn   Churn_Month
1   190.6   236.6    1         3.0
2   127.5   385      0         0.0
3   365     319.3    1         12.0
4   269.3   264.3    0         0.0
5   285.6   224.6    1         4.0

1 个答案:

答案 0 :(得分:1)

此处需要一些其他详细信息。首先,当Churn == 1假设客户离开时。使用df2,您可以确定他们离开的月份,并删除之后发生的所有数据。从那里开始,在分组,聚合和过滤数据方面非常简单。

# merge
df3 = df1.merge(df2)

# convert DATE to datetime
df3.DATE = pd.to_datetime(df3.DATE)

# filter rows where month of (DATE is <= Churn_Month and Churn == 1)
# or Churn == 0
df3 = df3.loc[
    ((df3.Churn == 1) & (df3.DATE.dt.month <= df3.Churn_Month)) |
    (df3.Churn == 0)
].copy()

# sort values ascending
df3.sort_values([
    'ID',
    'DATE',
    'P1',
    'P2',
    'Churn',
    'Churn_Month'
], inplace=True)

# groupby ID, Churn
# take last 3 DATEs
# merge with original to filter rows
# group on ID, Churn, and Churn_Month
# average P1 and P2
# reset_index to get columns back
# round results to 1 decimal at the end
df3.groupby([
    'ID',
    'Churn'
]).DATE.nth([
    -1, -2, -3
]).reset_index().merge(df3).groupby([
    'ID',
    'Churn',
    'Churn_Month'
])[[
    'P1',
    'P2'
]].mean().reset_index().round(1)

结果

   ID  Churn  Churn_Month     P1     P2
0   1      1          3.0  190.7  236.7
1   2      0          0.0  127.5  385.0
2   3      1         12.0  365.0  319.3
3   4      0          0.0  269.3  264.3
4   5      1          4.0  285.7  224.7
相关问题