为什么这个条件lambda函数不返回预期的结果?

2024-06-16 10:27:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我还不擅长使用Python和熊猫。我正在努力改进关键字评估。我女儿看起来像这样

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)

函数使用work将关键字附加到列,然后基于匹配项创建1或0。该函数还创建一个带有“word+keyword”的列,并为每行创建单词或“skip me”。你知道吗

我希望申请书能像这样工作

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'

有人能帮我解释一下为什么在我试图排除“skip me”字符串时会显示它们吗?你知道吗


Tags: key函数indfcol关键字descriptionkeyword
1条回答
网友
1楼 · 发布于 2024-06-16 10:27:48

is运算符(和is not)检查引用相等性。你知道吗

应该使用相等运算符,它将为大多数基本体检查值相等:

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

相关问题 更多 >