1

我使用以下代码消除了我的 df 中在各自的列名中包含“OBJ”的所有列:

d = pd.read_csv(url) 
df = d[d.columns.drop(list(d.filter(regex='OBJ')))]

我确实想消除列名中包含字符“OBJ”的所有变量,但名为“REV_OBJ”的特定变量除外。

有没有办法可以消除除“REV_OBJ”之外的所有“OBJ”?

4

2 回答 2

1

(个人喜好)这更具可读性:

cols = [col for col in df.columns if not 'OBJ' in col or col=='REV_OBJ']
于 2020-06-22T16:17:36.367 回答
0

您可以使用列表推导,并且可以拥有一组包含要删除的所有元素的集合。

to_remove = set([col for col in df.columns if "obj" in col.lower()]) - {'REV_OBJ'}
df.drop(to_remove, axis = 1, inplace = True)
于 2020-06-22T16:28:11.470 回答