【发布时间】:2017-08-26 04:03:33
【问题描述】:
这里对 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')
这会给我带来错误。
我想我只是把事情复杂化了,肯定有一些我不知道的非常简单的方法。 非常感谢任何帮助!
到目前为止我读过的帖子(不限于此列表,因为我已经关闭了许多窗口):
【问题讨论】:
-
您应该用“panda”标记您的问题。这不是纯 Python。