python - 数据框:在 if else 函数的新列中添加列出的值
问题描述
我正在寻找根据条件为我的 customer_id 分配的类别。如何从此函数在新列中设置值:
# customers categories based on rfm segmentation
cat = ["champion", "loyal", "big spenders", "almost lost", "hibernating", "lost cheap", "uncategorized"]
def customers_cat(rfm, f, m):
if rfm == '444':
return cat[0]
if f == 4:
return cat[1]
if m == 4 :
return cat[2]
if rfm == '244':
return cat[3]
if rfm == '144':
return cat[4]
if rfm == '111':
return cat[5]
else:
return cat[6]
我想要什么:我的数据框 df_cat 得到一个新列 df_cat['categories'] 根据函数中的条件,值等于 cat 列表。
df_cat['categories'] = customers_cat(df_cat['rfm_score'],
df_cat['f_score'],
df_cat['m_score'])
错误 =>
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
解决方案
这将逐行读取数据帧。axis=1
如果你想逐行使用:
df_cat['categories'] = df_cat.apply(lambda row: customers_cat(row['rfm_score'],row['f_score'],row['m_score']), axis=1)
如果您只使用一列,那么您可以使用。
df_cat['categories'] = df_cat['rfm_score'].apply(lambda row: customers_cat(row), axis=0)
推荐阅读
- drupal-8 - D8覆盖核心类
- java - JavaFX FXML - 使用 fx:id 获取 MenuItem
- html - 如何在AngularJS中循环多个表TH
- python - 用ffmpeg切割多个片段
- jsf - Liferay 7 JSF 动作未触发
- python - 电影评论类别错误 - NTLK
- symfony - Symfony3 以一种形式持久化每个 ManytoOne 实体字段?
- ms-word - 如何使用 word addin 在页眉中插入文档页码?
- android - 错误:无效的方法声明;android 所需的返回类型
- kubernetes - 我们如何使用 Kubernetes 创建服务依赖项