2

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

the man
  • 1,131
  • 1
  • 8
  • 19
  • What kind of is this? How did you end up with 100+ columns? – AMC Feb 13 '20 at 01:44
  • Does this answer your question? [Selecting pandas column by location](https://stackoverflow.com/questions/14941097/selecting-pandas-column-by-location) – AMC Feb 13 '20 at 01:44

4 Answers4

3

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)
GWW
  • 43,129
  • 11
  • 115
  • 108
  • 1
    You have an extra set of brackets: `df.drop(df.columns[15:30], axis=1)` is the correct syntax. Also, for the *last* 15 columns (as requested by OP) you can use `df.columns[-15:]`. – filbranden Feb 13 '20 at 00:44
  • 1
    Thanks for the catch. I should have paid better attention – GWW Feb 13 '20 at 00:49
  • 1
    Thanks for fixing! Yours was the best answer, just needed a small fix. – filbranden Feb 13 '20 at 00:55
2

Dropping the last 15 columns from a dataframe:

df = df.iloc[:, :-15]
σηγ
  • 1,294
  • 1
  • 8
  • 15
0

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)

enter image description here

As long as you can easily use your column index, this should work for your purposes.

Jeff Coldplume
  • 343
  • 1
  • 13
0

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)
Josiah
  • 26
  • 3