KristiLuna
KristiLuna

Reputation: 1903

Pandas - Delete multiple columns based on column position

I have a dataframe with an index, and with 19 columns that don't have column names. I want to keep the 3rd, 4th, 5th and 7th columns and drop the rest. I've tried this that is dropping the columns and leaving the 4 I need, but is there a cleaner way?

ds_drop1 = df.drop(df.columns[[0, 1]], axis = 1, inplace = True)
ds_drop1 = df.drop(df.columns[[5]], axis = 1, inplace = True)
ds_drop1 = df.drop(df.columns[[7, 8 , 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]], axis = 1, inplace = True)

Upvotes: 1

Views: 233

Answers (2)

DaveB
DaveB

Reputation: 452

Use .iloc for specific column or row locations. Note that the column positions are zero-indexed, so [2:6:7] will return the 3rd, 4th, 5th and 6th columns. The first : selects all rows:

Update based on your question - this will include the 7th column:

ds_drop1 = df.iloc[:,2:6,7]

Upvotes: 0

BENY
BENY

Reputation: 323226

In your case doing numpy.r_ with iloc(Adding copy for prevent the future copy warning)

#import numpy as np
out = df.iloc[:,np.r_[3:6,7]].copy()

Upvotes: 1

Related Questions