首页 > 解决方案 > 数据框:在 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().

标签: pythonpython-3.xdataframe

解决方案


这将逐行读取数据帧。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)

推荐阅读