【问题标题】:Why does this conditional lambda function not return the expected result?为什么这个条件 lambda 函数没有返回预期的结果?
【发布时间】:2017-12-22 13:08:24
【问题描述】:

我仍然不擅长使用 python 和 pandas。我正在努力改进关键字评估。我的DF长这样

Name  Description 
Dog   Dogs are in the house
Cat   Cats are in the shed
Cat   Categories of cats are concatenated

I am using a keyword list like this ['house', 'shed', 'in']

我的 lambda 函数如下所示

keyword_agg = lambda x: ' ,'.join x if x is not 'skip me' else None

我正在使用一个函数来识别关键字匹配的每一行并为其评分

def foo (df, words):
    col_list = []
    key_list= []
    for w in words:
        pattern = w
        df[w] = np.where(df.Description.str.contains(pattern), 1, 0)
        df[w +'keyword'] = np.where(df.Description.str.contains(pattern), w, 
                          'skip me')
        col_list.append(w)
        key_list.append(w + 'keyword')
    df['score'] = df[col_list].sum(axis=1)
    df['keywords'] = df[key_list].apply(keyword_agg, axis=1)

该函数将关键字附加到使用作品的列,然后根据匹配创建 1 或 0。该函数还使用“单词+关键字”创建一列,并为每一行创建单词或“跳过我”。

我希望申请能像这样工作

df['keywords'] = df[key_list].apply(keyword_agg, axis=1)

返回

Keywords
in, house
in, shed
None

相反,我得到了

Keywords
in, 'skip me' , house
in, 'skip me', shed
'skip me', 'skip me' , 'skip me'

有人可以帮我解释为什么在我尝试排除它们时会显示“跳过我”字符串吗?

【问题讨论】:

标签: python pandas lambda conditional


【解决方案1】:

is 运算符(和is not)检查引用相等性

您应该使用对大多数原语进行检查的相等运算符值相等

lambda x: ' ,'.join(x) if x <b>!=</b> 'skip me' else None

【讨论】:

  • 很确定这是一个 SyntaxError。
  • @MSeifert 实际上,我认为这不是操作想要的。我认为他们实际上想要' ,'.join(s for s in x if s != 'skip me')
  • 不过很难说。他们的例子并不是真正的 MCVE。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-27
  • 2021-08-24
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 2013-03-25
  • 1970-01-01
相关资源
最近更新 更多