Removing single and range of columns in pandas [duplicate]

被刻印的时光 ゝ 提交于 2020-06-12 08:52:27

问题


What is the fastest way to drop columns[3] and columns[9:15]? (I'm only able to remove the columns in 2 steps using the df.drop method)

    1  2  3  4  5  6 ..  n
A   x  x  x  x  x  x ..  x
B   x  x  x  x  x  x ..  x
C   x  x  x  x  x  x ..  x 

回答1:


You can, in fact, use pd.DataFrame.drop in one step. You can use np.r_ to combine multiple indices and ranges. Here's a demo:

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')



回答2:


Use as below:

>>> 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



回答3:


Using simple loc and isin

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

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

but np.r_ is so nice I'd go with it ;)



来源:https://stackoverflow.com/questions/52245582/removing-single-and-range-of-columns-in-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!