首页 > 解决方案 > Pandas.Series.Str.Find 在列表中与 x 混合

问题描述

下午好!

长话短说,我正在尝试根据评论数据集对手机的某些功能进行情感分析。我正在将它与 .loc 函数协调,它以前工作过,但这是一个特定的列表而不是字符串。我正在尝试将其链接到列表中的任何 x,其中 x 是一个列表。

这是我所拥有的:

Battery = ['battery', 'charge', 'juice', 'talk time', 'hours', 'minutes']
batt = apple['Reviews'].str.lower().str.find(x in Battery)!=-1

返回的错误是:

AttributeError: Can only use .str accessor with string values.

我这样做是因为它不喜欢我只是在电池中放入电池而不是 x。

有什么建议么?再次感谢!

如果我运行分配的变量,预期的输出将是所有具有任何关键字的行。(电池内的 x)。因此,任何带有充电、果汁等内容的行都会弹出。

标签: pythonpandasstringlistattributeerror

解决方案


如果apple['Review']只是一列字符串,您可以检查str.contains().

鉴于这些Batteryapple​​:

Battery = ['battery', 'charge', 'juice', 'talk time', 'hours', 'minutes']
apple = pd.DataFrame({'Review': ['abc battery xyz', 'foo bar', 'orange juice bar', 'talk time']})

#              Review
# 0   abc battery xyz
# 1           foo bar
# 2  orange juice bar
# 3         talk time

这将是batt输出:

batt = apple[apple['Review'].str.lower().str.contains('|'.join(Battery))]

#              Review
# 0   abc battery xyz
# 2  orange juice bar
# 3         talk time

如果是一列列表,您可以在检查之前apple['Review']先将它们加入:str.join(' ')str.contains()

batt = apple[apple['Review'].str.join(' ').str.lower().str.contains('|'.join(Battery))]

推荐阅读