按字符串子字符串的列过滤 Pandas 数据框[重复]

问题描述 投票:0回答:1

我正在尝试使用列中的字符串值是数据框外部字符串的子字符串的条件来过滤数据框。下面的例子:

df = [['a', 'b', 'c'], ['你好', '再见', '你好']]

reference_str =“你好”

输出 = ['a','c']

一种方法可能是使用正则表达式迭代列中的每个值。想知道是否有更有效的方法来做到这一点。预先感谢。

python pandas dataframe substring contains
1个回答
0
投票

如果你想匹配完整的单词,你可以在分割字符串上使用

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
© www.soinside.com 2019 - 2024. All rights reserved.