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)
CodePudding user response:
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()
CodePudding user response:
Use .iloc for specific column or row locations. Note that the column positions are zero-indexed, so [2:6] will return the 3rd, 4th, 5th and 6th columns. The first : selects all rows:
ds_drop1 = df[:,2:6]
