gpt4 book ai didi

python - 数据帧 : add listed values in a new column from if else function

转载 作者:太空宇宙 更新时间:2023-11-03 21:08:41 25 4
gpt4 key购买 nike

我正在寻找根据条件为我的 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)

关于python - 数据帧 : add listed values in a new column from if else function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55218916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com