【问题标题】:negative lookbehind when filtering pandas columns过滤熊猫列时的负面回顾
【发布时间】:2022-11-10 17:57:51
【问题描述】:

考虑这个简单的例子

import pandas as pd

df = pd.DataFrame({'good_one' : [1,2,3],
                   'bad_one' : [1,2,3]})

Out[7]: 
   good_one  bad_one
0         1        1
1         2        2
2         3        3

在这个人工示例中,我想过滤不以bad 开头的列。我可以使用.filter() 在熊猫列上使用正则表达式条件。但是,我无法让它在消极的后视下工作。

看这里

df.filter(regex = 'one')
Out[8]: 
   good_one  bad_one
0         1        1
1         2        2
2         3        3

但现在

df.filter(regex = '(?<!bad).*')
Out[9]: 
   good_one  bad_one
0         1        1
1         2        2
2         3        3

不做任何事情。我错过了什么吗?

谢谢

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    IIUC 用途:

    df = df.filter(regex=r'^(?!.*bad).*$')
    print (df)
       good_one
    0         1
    1         2
    2         3
    

    【讨论】:

      猜你喜欢
      • 2013-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-30
      • 2016-05-19
      • 1970-01-01
      • 2016-09-07
      • 2020-11-12
      相关资源
      最近更新 更多