我正在尝试使用列中的字符串值是数据框外部字符串的子字符串的条件来过滤数据框。下面的例子:
df = [['a', 'b', 'c'], ['你好', '再见', '你好']]
reference_str =“你好”
输出 = ['a','c']
一种方法可能是使用正则表达式迭代列中的每个值。想知道是否有更有效的方法来做到这一点。预先感谢。
isin
:
df = pd.DataFrame({'col1': ['a', 'b', 'c'],
'col2': ['hello', 'bye', 'hello']})
reference_str = "hello there"
out = df[df['col2'].isin(reference_str.split())]
print(out)
输出:
col1 col2
0 a hello
2 c hello