【问题标题】:Dataframe : add listed values in a new column from if else function数据框:在 if else 函数的新列中添加列出的值
【发布时间】:2019-03-18 10:09:26
【问题描述】:

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

【问题讨论】:

  • 现在您正在将整个系列与函数中的数字进行比较
  • 我不太明白你的if else逻辑
  • 也许我应该添加以前的代码 Nihal 的答案允许添加值。

标签: python python-3.x dataframe


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 2017-03-14
    相关资源
    最近更新 更多