首页 > 解决方案 > How to filter a pandas column by list of strings?

问题描述

The standard code for filtering through pandas would be something like:

output = df['Column'].str.contains('string')
strings = ['string 1', 'string 2', 'string 3']

Instead of 'string' though, I want to filter such that it goes through a collection of strings in list, "strings". So I tried something such as

output = df['Column'].str.contains('*strings')

This is the closest solution I could find, but did not work How to filter pandas DataFrame with a list of strings

Edit: I should note that I'm aware of the | or operator. However, I'm wondering how to tackle all cases in the instance list strings is changing and I'm looping through varying lists of changing lengths as the end goal.

标签: pythonpandaslist

解决方案


You can create a regex string and search using this string.

Like this: df['Column'].str.contains('|'.join(strings),regex=True)


推荐阅读