Reputation: 1391
Say I have a data frame with 100+ columns, how would I go about dropping, say, the last 15 columns?
Is there a better way than typing: df.drop([column1,column2,...,column15])
? I have to input the names of all of the columns here. Is there not a way I can sort of slice, like something like [column1 : column15]
?
Upvotes: 2
Views: 1065
Reputation: 44093
If you know the indexes of the columns you want to drop you could use
df.drop(df.columns[15:30], axis=1)
As mentioned in the comment by @fillbranden I should have shown you how to delete the last 15 columns with:
df.drop(df.columns[-15:], axis=1)
Upvotes: 3
Reputation: 26
Drop the last X columns if you don't know the specific column indexes:
cols = list(range(-1, -10, -1)) # Drop last 10 columns
df.drop(df.columns[cols], axis = 1)
Upvotes: 0
Reputation: 353
Try this code with the made up dataframe:
df = pd.DataFrame(np.random.randint(0,100, size= (100, 15)), columns=list('ABCDEFGHIJKLMNO'))
In this case I dropped the last 5 columns using:
df.drop(df.iloc[:,10:15], inplace=True, axis=1)
print(df)
As long as you can easily use your column index, this should work for your purposes.
Upvotes: 0