如何解决python for col in col if - 排除特定字符串
我正在尝试拆分一些数据帧,并且有许多数据帧要拆分/创建,因此我正在尝试使用 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 很陌生,不知道还能尝试什么?
预先感谢您的时间和精力!
解决方法
也不能评论(没有足够的声誉,几天前才注册),很抱歉发布另一个答案。使用以下理解:
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']
,
使用features = [col for col in column_names if 'recovery' not in col.contains('recovery')]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。