我们可以使用str.contains在多个列中查找值吗?

2024-04-20 07:46:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含多个列的dataframe,并希望基于其他列中的值创建新列(列“type”)。对于值的分类,我使用pd.nd.where和str.contains

目前,我的代码正在运行。但是我对每一列使用的每个过滤器。相反,我想对多个列使用一个过滤器

df.type = pd.np.where(df.column1.str.contains('|'.join(filter1), case = False), "Type1", 
    pd.np.where(df.column2.str.contains('|'.join(filter1), case = False), "Type1", 
    pd.np.where(df.column3.str.contains('|'.join(filter1), case = False), "Type1", 
    "TypeDifferent")))

我希望产量要短得多。像这样:

df.type = pd.np.where(df[[column1, column2, column3]].str.contains('|'.join(filter), case = False), "Type1", "TypeDifferent")))

Tags: false过滤器dftypenpwherepdcase