python - 新近度和频率分割
问题描述
我从我的 RFM 模型生成了 csv 格式的新近度和频率输出。我想以这种方式分割输出;
1) Recency
R1 Between 181 and 360 days
R2 Between 121 and 180 days
R3 Between 61 and 120 days
R4 Between 31 and 60 days
R5 Last 30 days
对于频率,
2) Frequency (number of purchases in the last 12 months):
F1 1 time
F2 Between 2 and 5 times
F3 Between 6 and 9 times
F4 Between 10 and 11 times
F5 12 times or more
我无法找到有关如何使用上述输出创建两个新列的解决方案。
这是我的样本数据;
df_rf->
frequency recency
1 179
1 158
1 61
2 82
2 314
输出应该是这样的,
frequency recency Frequency_label Recency_label
1 179 F1 R2
1 158 F1 R2
1 61 F1 R3
2 82 F2 R3
2 314 F2 R1
对此的任何帮助将不胜感激。
预先感谢您的支持!
解决方案
不要从@Sonia Samipillai 的回答中拿走任何东西,这看起来不错(我很高兴你得到了你需要的帮助!),但我想展示另一种方法来完成同样的事情,这可能会使整体代码更整洁,尤其是在有很多值要替换的情况下。
为此,我们定义了我们想要在一些字典中进行的替换,然后转向pandas 的 between() 函数。
在这种情况下(假设您想保留原始列并添加新版本 - 否则会简单得多!),我想我会写如下内容:
import numpy as np
freq_cat_mapping = {(1, 1): 'F1', (2, 5): 'F2', (6, 9): 'F3', (10, 11): 'F4', (12,None,13): 'F5'}
frequency_cats = df_rf['frequency']
for range, value in freq_cat_mapping.items():
if len(range) == 2:
frequency_cats = np.where(df_rf['frequency'].between(*range), value, frequency_cats)
else:
# This got a bit messy since I had to improvise some Q&D logic to handle the open intervals...but it could obviously be improved.
if range[-1] > range[0]:
cond = df_rf['frequency'] >= range[0]
else:
cond = df_rf['frequency'] <= range[0]
frequency_cats = np.where(cond, value, frequency_cats)
recency_cat_mapping = {(0, 30): 'R1', (31, 60): 'R2', (61, 120): 'R3', (121, 180): 'R4', (181, 360): 'R5'}
recency_cats = df_rf['recency']
for range, value in recency_cat_mapping.items():
recency_cats = np.where(df_rf['recency'].between(*range), value, recency_cats)
#Finally, concatanate the new cols
df_rf['frequency_label'] = frequency_cats
df_rf['recency_label'] = recency_cats
推荐阅读
- android - Webview 图像不会在真实设备上加载
- singlestore - Memsql 工作室显示黑屏
- python - 使用 Visual Studio Code 为外部 python 解释器设置配置文件
- laravel - 区分大小写在带有大写字母的服务器上的 sluggable 中不起作用
- javascript - 传递事件和 $event 之间有区别吗?
- plex - NZBGet - 安装问题。nzbget:找不到命令
- node.js - Nodemon中的神秘参数-r
- python - TypeError: wrapper() 接受 1 个位置参数,但给出了 2 个
- elasticsearch - 使用输入数组进行 Elasticsearch 过滤,其中
- c - 如何将 2 个大数字乘以字符串(使用之前添加 2 个字符串的函数)?C