删除基于字符串条件的列

2024-05-20 01:52:55 发布

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

如何根据名称中的某个字符串删除dataframe列?在

示例:

           house1    house2    chair1  chair2
index
  1         foo       lee       sam      han
  2         fowler    smith     had      sid
  3         cle       meg       mag      mog

我要删除字符串中包含“chair”的列。 如何有效地做到这一点? 谢谢。在


Tags: 字符串名称示例dataframeindexfoosamsmith
3条回答
df.drop([col for col in df.columns if 'chair' in col],axis=1,inplace=True)

这应该做到:

df.drop(df.columns[df.columns.str.match(r'chair')], axis=1)

enter image description here


定时

MaxU方法2

enter image description here

更新2:

In [315]: df
Out[315]:
   3M110%  3M80% 6M90% 6M95% 1N90% 2M110% 3M95%
1     foo    lee   sam   han   aaa    aaa   fff
2  fowler  smith   had   sid   aaa    aaa   fff
3     cle    meg   mag   mog   aaa    aaa   fff

In [316]: df.loc[:, ~df.columns.str.contains('90|110')]
Out[316]:
   3M80% 6M95% 3M95%
1    lee   han   fff
2  smith   sid   fff
3    meg   mog   fff

更新:

^{pr2}$

原始答案:

以下是一些备选方案:

In [37]: df.drop(df.filter(like='chair').columns, 1)
Out[37]:
   house1 house2
1     foo    lee
2  fowler  smith
3     cle    meg

In [38]: df.filter(regex='^(?!chair.*)')
Out[38]:
   house1 house2
1     foo    lee
2  fowler  smith
3     cle    meg

相关问题 更多 >