【发布时间】: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'
有人可以帮我解释为什么在我尝试排除它们时会显示“跳过我”字符串吗?
【问题讨论】:
-
is not是身份。你想要x != "skip me"见Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result? -
首先,你为什么要使用
lambda?您将其分配给一个名称,从而消除了lambda具有的唯一优势:它是匿名的。其次,我很确定keyword_agg = lambda x: ' ,'.join x if x is not 'skip me' else None是一个 SyntaxError。
标签: python pandas lambda conditional