使用Columns.Str.Startswith删除多个列

2024-10-02 08:21:03 发布

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

我有一个204行x507列的数据集。据我所知,为了删除包含单词“Dog”的列,例如,您可以使用:

df.loc[:,~df.columns.str.startswith('Dog')]

我还了解到,您可以通过使用以下“str.contains”代码,使用多个条件删除列,例如“Dog”和“Cat”:

df.loc[:,~df.columns.str.contains('Dog|Cat')]

但是,当您将“|”(or)函数应用于下面的“columns.str.startswith”时,它似乎不起作用,并且输出为204行x 0列

df.loc[:,~df.columns.str.startswith('Dog|Cat')]

Out204 rows × 0 columns

这是为什么?是否有一种方法可以使用“df.columns.str.startswith”函数使用多个条件删除列?


Tags: orcolumns数据函数代码df条件单词
2条回答

对于一些字符串,我更喜欢正则表达式方法:

 df.loc[:, ~df.columns.str.match('^(Dog|Cat).*')]

如果要在^{}中使用多个值,请使用tuple如下:

df.loc[:,~df.columns.str.startswith(('Dog', 'Cat'))]

相关问题 更多 >

    热门问题