题解 | #某店铺用户消费特征评分#
某店铺用户消费特征评分
https://www.nowcoder.com/practice/200c824e9ed4428491c27d65ec56067d
import pandas as pd sales = pd.read_csv('sales.csv') pd.set_option('display.max_columns', None)# 显示所有的列,而不是以……显示 pd.set_option('display.max_rows', None)# 显示所有的行,而不是以……显示 pd.set_option('display.width', None) # 不自动换行显示 # pd.quantile()为求分位数操作,需要自行在里面添加数值 # 默认值: # quantile( q=0.5, axis: 'Axis' = 0, numeric_only: 'bool' = True, interpolation:'str' = 'linear') # 第一步:先定义分位数 r1 = sales['recency'].quantile(q = 0.25) r2 = sales['recency'].quantile(q = 0.5) r3 = sales['recency'].quantile(q = 0.75) f1 = sales['frequency'].quantile(q = 0.25) f2 = sales['frequency'].quantile(q = 0.5) f3 = sales['frequency'].quantile(q = 0.75) m1 = sales['monetary'].quantile(q = 0.25) m2 = sales['monetary'].quantile(q = 0.5) m3 = sales['monetary'].quantile(q = 0.75) # 第二步:分别定义分段函数 def r_value(x): if x <= r1: return 4 elif x > r1 and x <= r2: return 3 elif x > r2 and x <= r3: return 2 else: return 1 def f_value(x): if x >= f3: return 4 elif x >= f2 and x < f3: return 3 elif x > f1 and x <= f2: return 2 else: return 1 def m_value(x): if x >= m3: return 4 elif x >= m2 and x < m3: return 3 elif x > m1 and x <= m2: return 2 else: return 1 # 第三步: 用apply映射 sales['R_Quartile'] = sales['recency'].apply(r_value) sales['F_Quartile'] = sales['frequency'].apply(f_value) sales['M_Quartile'] = sales['monetary'].apply(m_value) # 结果 print(sales.head())