列表的哪个元素的字符串包含 pandas dataframe

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

这是这个问题的后续问题,在其中一个答案中,它显示以下内容可以测试数据框列是否包含列表中的值。

df4 = pd.DataFrame({'col': ['foo abc', 'foobar xyz', 'bar32', 'baz 45']})
terms = ['foo', 'baz']
df4[df4['col'].str.contains('|'.join(terms))]

此外,我需要找出列表中的哪一项包含在该列中。在此示例中,我希望输出如下所示。有没有一种简单的方法可以在不使用循环的情况下实现这一目标?

1 (since containing foo), 1, NA (i.e., doesn't contain any from the list), 2
pandas
1个回答
0
投票
out = (df4['col'].str.extract(f"({'|'.join(terms)})")[0]
                 .map({k: n for n, k in enumerate(terms, 1)})
)

0    1.0
1    1.0
2    NaN
3    2.0
Name: 0, dtype: float64
© www.soinside.com 2019 - 2024. All rights reserved.