数据框:从if else函数将列出的值添加到新列中

时间:2019-03-18 10:09:27

标签: python python-3.x dataframe

我正在根据条件为我的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'],其中的值基于函数中的条件例如为猫列表。

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().

1 个答案:

答案 0 :(得分:0)

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