如果子字符串列表中的任何值包含在数据框中的任何列中,则过滤行

Filter for rows if any value in a list of substrings is contained in any column in a dataframe

假设我有一个数据帧 df 为:

df = pd.DataFrame({'Index': [1, 2, 3, 4, 5],
                   'Name': ['A', 'B', 100, 'C', 'D'],
                   'col1': [np.nan, 'bbby', 'cccy', 'dddy', 'EEEEE'],
                   'col2': ['water', np.nan, 'WATER', 'soil', 'cold air'],
                   'col3': ['watermelone', 'hot AIR', 'air conditioner', 'drink', 50000],
                  'Results': [1000, 2000, 3000, 4000, 5000]})


Out

Index  Name  col1     col2         col3           Results
    1  A     NaN    water       watermelone        1000
    2  B     bbbY    NaN         hot AIR           2000
    3  100   cccY    water       air conditioner   3000
    4  C     dddf    soil        drink             4000
    5  D     EEEEE   cold air    50000             5000

我有一个列表:matches = ['wat','air']

如何在 matches.

中选择包含 icol1col2col3 的所有行

预期输出:

Index  Name  col1     col2         col3           Results
    1  A     NaN     water       watermelone       1000
    2  B     bbbY    NaN         hot AIR           2000
    3  100   cccY    water       air conditioner   3000

    5  D     EEEEE   cold air    50000              5000

您可以使用 .T 转置数据框并使用 str.contains 检查值 column-wise 然后转回(另外 str.contains 可以将多个值传递给 if用 | 分隔,这就是为什么我将列表更改为带有 matches = '|'.join(matches)).

的字符串的原因

转置数据帧的好处是您可以使用 column-wise pandas 方法而不是遍历行或长 lambda x: 列表理解。 This technique should have good performancelambda x 相比 axis=1 答案:

# df = df.set_index('Index')
matches = ['wat','air']
matches = '|'.join(matches)
df = df.reset_index(drop=True).T.fillna('')
df = df.T[[df[col].str.lower().str.contains(matches).values.any() for col in df.columns]]
df
Out[1]: 
  Name   col1      col2             col3
0    A            water      watermelone
1    B   bbbY                    hot AIR
2    B   cccY     water  air conditioner
4    D  EEEEE  cold air              eat

也试试这个:

df = df[df['col1'].str.contains('|'.join(matches))|df['col2'].str.contains('|'.join(matches))|df['col3'].str.contains('|'.join(matches))]

打印:

  Name   col1      col2             col3
1    A   aadY     water      watermelone
2    B   bbbY       air          hot AIR
3    B   cccY     water  air conditioner
5    D  EEEEE  cold air              eat