如何按多个关键字删除一系列列

2024-09-28 16:58:51 发布

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

我收到一个熊猫数据帧。 它充满了不必要的功能,我想删除。 现在我在做下面的事情,这是肮脏的 我怎么能用一种更像Python的方式

 features_to_include= mydf.columns.tolist()
 features_to_include=[f for f in features_to_include if 'stopword1' not in f]

 features_to_include=[f for f in features_to_include if 'stopwordN' not in f]

[。。。其他90个]

    features_to_include=[f for f in features_to_include if 'password1' in f]
    features_to_include=[f for f in features_to_include if 'passwordN' in f]

[。。。其他90个]

编辑:'stopword1'和'password1'在X.columns中不是 X.columns的示例名称可以是:feature99_stopword1


Tags: columnsto数据in功能forifinclude
2条回答

您可以尝试使用^{}

df.filter(regex='password|stopword1', axis=1)

或者如果我们有一份清单:

cols = ['password','passwordN','stopword1','stopwordN']
mydf.filter(regex='|'.join(cols), axis=1)

我认为需要^{}

L = ['stopword1','stopwordN','password1', 'passwordN']
#thanks roganjosh for suggestion
L = set(['stopword1','stopwordN','password1', 'passwordN'])

mydf = mydf.loc[:, mydf.columns.str.contains('|'.join(L))]

样本

mydf = pd.DataFrame({'feature99_stopword1':list('abcdef'),
                   'feature99_stopword':[4,5,4,5,5,4],
                   'C':[7,8,9,4,2,3],
                   'd_stopword1':[1,3,5,7,1,0],
                   'password1':[5,3,6,9,2,4],
                   'F':list('aaabbb')})
print (mydf)
  feature99_stopword1  feature99_stopword  C  d_stopword1  password1  F
0                   a                   4  7            1          5  a
1                   b                   5  8            3          3  a
2                   c                   4  9            5          6  a
3                   d                   5  4            7          9  b
4                   e                   5  2            1          2  b
5                   f                   4  3            0          4  b

L = ['stopword1','stopwordN','password1', 'passwordN']
mydf = mydf.loc[:, mydf.columns.str.contains('|'.join(L))]
print (mydf)
  feature99_stopword1  d_stopword1  password1
0                   a            1          5
1                   b            3          3
2                   c            5          6
3                   d            7          9
4                   e            1          2
5                   f            0          4

相关问题 更多 >