Python 删除pandas中的单个列和列范围

Python 删除pandas中的单个列和列范围,python,python-3.x,pandas,dataframe,indexing,Python,Python 3.x,Pandas,Dataframe,Indexing,删除列[3]和列[9:15]的最快方法是什么? (我只能使用df.drop方法分两步删除列) 使用方法如下: >>> df A B C D 0 0 1 2 3 1 4 5 6 7 2 8 9 10 11 >>> df.drop(['B', 'C'], axis=1) A D 0 0 3 1 4 7 2 8 11 事实上,你可以一步到位。可以使用组合多个索引和范围。下面是一个演示: d

删除
列[3]
列[9:15]
的最快方法是什么? (我只能使用
df.drop
方法分两步删除列)

使用方法如下:

>>> df
   A  B   C   D
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11

>>> df.drop(['B', 'C'], axis=1)
   A   D
0  0   3
1  4   7
2  8  11
事实上,你可以一步到位。可以使用组合多个索引和范围。下面是一个演示:

df = pd.DataFrame(np.random.random((3, 20)))

print(df.columns)  # RangeIndex(start=0, stop=20, step=1)

res = df.drop(np.r_[3, 9:15], 1)

print(res.columns)

# Int64Index([0, 1, 2, 4, 5, 6, 7, 8, 15, 16, 17, 18, 19], dtype='int64')

使用简单的
loc
isin

cols = df.columns.tolist()
to_remove = cols[9:15] + [cols[3]]

df.loc[:, ~df.columns.isin(to_remove)]
但是
np.r
太好了,我愿意接受它;)

相关的:
cols = df.columns.tolist()
to_remove = cols[9:15] + [cols[3]]

df.loc[:, ~df.columns.isin(to_remove)]