# 用户核销率(领券消费数/领券数) feature_user[prefixs+'receive_consume_rate'] = feature_user[prefixs+'receive_consume_cnt'].astype('float')/feature_user[prefixs+'receive_cnt'].astype('float')改写代码功能不变
时间: 2024-03-21 09:44:36 浏览: 56
下面是改写后的代码:
```
prefixs = 'o2o_'
feature_user[prefixs+'receive_consume_rate'] = feature_user.apply(lambda x: x[prefixs+'receive_consume_cnt']/x[prefixs+'receive_cnt'] if x[prefixs+'receive_cnt'] != 0 else 0, axis=1)
```
这里使用了 `apply` 函数和 lambda 表达式,将原先的除法运算改为了一个条件语句,当领券数为0时,将用户核销率设为0,避免了除以0的错误。
相关问题
# 用户核销率(领券消费数/领券数) feature_user[prefixs+'received_consume_rate'] = feature_user.apply(lambda x: x[prefixs+'received_consume_cnt']/x[prefixs+'received_cnt'] if x[prefixs+'received_cnt'] != 0 else 0, axis=1) # 用户在多少不同商家领取优惠券 pivot = pd.pivot_table(data[data['Date_received'].notnull()][['User_id', 'Merchant_id']], index=keys1, values='Merchant_id', aggfunc=lambda x:len(set(x))) pivot = pd.DataFrame(pivot).rename(columns={'Merchant_id':prefixs + 'received_differ_merchant'}).reset_index() feature_user = pd.merge(feature_user, pivot, on=keys1, how='left')改写代码,功能不变
# 用户核销率(领券消费数/领券数)
feature_user['received_consume_rate'] = feature_user['received_consume_cnt'] / feature_user['received_cnt'].apply(lambda x: x if x != 0 else 1)
# 用户在多少不同商家领取优惠券
pivot = data[data['Date_received'].notnull()][['User_id', 'Merchant_id']].groupby(keys1)['Merchant_id'].nunique().reset_index()
pivot = pivot.rename(columns={'Merchant_id': 'received_differ_merchant'})
feature_user = pd.merge(feature_user, pivot, on=keys1, how='left')
keys1 = ['User_id'] prefixs = 'history_' + '_'.join(keys1) + '_' # 用户核销率(领券消费数/领券数) feature_user[prefixs+'received_consume_rate'] = feature_user.apply(lambda x: x[prefixs+'received_consume_cnt']/x[prefixs+'received_cnt'] if x[prefixs+'received_cnt'] != 0 else 0, axis=1) # 用户在多少不同商家领取优惠券 pivot = pd.pivot_table(data[data['Date_received'].notnull()][['User_id', 'Merchant_id']], index=keys1, values='Merchant_id', aggfunc=lambda x:len(set(x))) pivot = pd.DataFrame(pivot).rename(columns={'Merchant_id':prefixs + 'received_differ_merchant'}).reset_index() feature_user = pd.merge(feature_user, pivot, on=keys1, how='left')改写代码 功能不变
keys1 = ['User_id']
prefixs = 'history_' + '_'.join(keys1) + '_'
# 用户核销率(领券消费数/领券数)
feature_user[prefixs + 'received_consume_rate'] = feature_user[prefixs + 'received_consume_cnt'] / feature_user[prefixs + 'received_cnt'].apply(lambda x: x if x != 0 else 1)
# 用户在多少不同商家领取优惠券
pivot = data[data['Date_received'].notnull()][['User_id', 'Merchant_id']].groupby(keys1)['Merchant_id'].nunique().reset_index()
pivot = pivot.rename(columns={'Merchant_id':prefixs + 'received_differ_merchant'})
feature_user = pd.merge(feature_user, pivot, on=keys1, how='left')
阅读全文