这里是Python的新手,对如何正确使用Python还不是很了解,所以请原谅我的愚蠢。
假设我们有这样一个数据框:
samp_data = pd.DataFrame([[1,'hello there',3],
[4,'im just saying hello',6],
[7,'but sometimes i say bye',9],
[2,'random words here',5]],
columns=["a", "b", "c"])
print(samp_data)
a b c
0 1 hello there 3
1 4 im just saying hello 6
2 7 but sometimes i say bye 9
3 2 random words here 5
然后我们设置了一个我们不想要的单词列表:
unwanted_words = ['hello', 'random']
我想编写一个函数来排除 b 列包含“unwanted_words”列表中的任何单词的所有行。所以输出应该是:
print(samp_data)
a b c
2 7 but sometimes i say bye 9
到目前为止我尝试过的包括使用内置的“isin()”函数:
data = samp_data.ix[samp_data['b'].isin(unwanted_words),:]
但这并不像我预期的那样排除行; 我尝试使用 str.contains() 函数:
for i,row in samp_data.iterrows():
if unwanted_words.str.contains(row['b']).any():
print('found matching words')
这会给我带来错误。
我想我只是把事情复杂化了,一定有一些我不知道的非常简单的方法。 非常感谢任何帮助!
到目前为止我读过的帖子(不限于此列表,因为我已经关闭了很多窗口):
请您参考如下方法:
您实际上非常接近解决方案。它使用 Series.str.contains 方法。请记住,它允许使用正则表达式:
samp_data[~samp_data['b'].str.contains(r'hello|random')]
结果将是:
Out [11]:
a b c
2 7 but sometimes i say bye 9
