按字符串子字符串的列过滤 Pandas 数据框

2024-05-31

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

df = [['a', 'b', 'c'], ['hello', 'bye', 'hello']]

reference_str = "hello there"

output = ['a','c']

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


如果你想匹配完整的单词,你可以使用isin https://pandas.pydata.org/docs/reference/api/pandas.Series.isin.html在分割字符串上:

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)

如果确实如此,您想匹配任何子字符串(例如'the' or 'el'应该匹配),然后你必须循环:

out = df[[x in reference_str for x in df['col2']]]

Output:

  col1   col2
0    a  hello
2    c  hello
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

按字符串子字符串的列过滤 Pandas 数据框 的相关文章

随机推荐