【问题标题】:python for col in col if - exclude specific stringpython for col in col if - 排除特定字符串
【发布时间】:2021-03-29 22:46:35
【问题描述】:

我正在尝试拆分一些数据帧,其中有许多要拆分/创建,所以我尝试使用 for 循环,但不能完全让它做我想做的事。

有一个数据框(我在下面将其称为 column_names),它只包含一些我希望它查看以排除 2 个特定列的较小数据框之间共有的列名。

我正在使用以下内容:

# target and features
target = ['rougher.output.recovery', 'final.output.recovery']
features = [col for col in column_names if ~col.str.contains('recovery')]

目标是将这些输入数据框,如下所示:

#dataframes for each step train and test targets
target_train, target_test = train_imp[target].values,test_imp[target].values
features_train, features_test = train_imp[features].values,test_imp[features].values

我正在尝试排除名称中包含 recovery 的列,但我并没有完全正确。

我试过了:

[col for col in train_test if col != ['rougher.output.recovery', 'final.output.recovery']

[col for col in train_test if not 'rougher.output.recovery' or 'final.output.recovery']

但他们实际上并没有排除我想要排除的列?

我也尝试过上面的 .contains,但它不起作用,坦率地说,我对 python 很陌生,不知道还能尝试什么?

提前感谢您的时间和精力!

【问题讨论】:

    标签: python for-loop string-matching


    【解决方案1】:

    也不能评论(名气不够,前几天刚注册),不好意思再发个答案。使用以下理解:

    features = [col for col in column_names if 'recovery' not in col]
    

    您的两次尝试也都可以纠正:

    [col for col in train_test if col not in ['rougher.output.recovery', 'final.output.recovery']
    
    [col for col in train_test if col != 'rougher.output.recovery' and col != 'final.output.recovery']
    

    【讨论】:

      【解决方案2】:

      使用features = [col for col in column_names if 'recovery' not in col.contains('recovery')]

      【讨论】:

      • 我收到错误“str object has no attribute 'contains'
      • 抱歉,拼写检查截断了我的答案...现在编辑
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-23
      • 1970-01-01
      • 1970-01-01
      • 2011-09-27
      • 2010-11-07
      • 2019-06-19
      • 2016-10-25
      相关资源
      最近更新 更多