0

I am trying to delete the following columns on my dataframe: 1,2,101:117,121:124,126.

So far the two ways I have found to delete columns is:

df.drop(df.columns[2:6],axis=1)
df.drop(df.columns[[0,3,5]],axis=1) 

however if I try

df.drop(df.columns[1,2,101:117,121:124],axis=1)

I get a "too many indices" error

I also tried this

a=df.drop(df.columns[[1,2]],axis=1)
b=a.drop(a.columns[99:115],axis=1)
c=b.drop(b.columns[102:105],axis=1)
d=c.drop(c.columns[103],axis=1)

but this isn't deleting the columns I'm wanting to for some reason.

Alex
  • 6,610
  • 3
  • 20
  • 38
  • 2
    This might be of some help - https://stackoverflow.com/questions/28538536/deleting-multiple-columns-based-on-column-names-in-pandas – Craicerjack Apr 02 '19 at 15:38
  • Maybe try deleting the columns in the opposite order? If you delete cols 1 and 2, col 99 becomes col 97. – dubbbdan Apr 02 '19 at 15:39
  • How single indices and ranges can be combined into a single list is explained here https://stackoverflow.com/a/14519521/5350621. In your case index = [1,2] + list(range(101, 117)) + ... and then df.drop(df.columns[index],axis=1). – David Apr 02 '19 at 15:45

3 Answers3

3

Use np.r_ to slice:

import numpy as np

df.drop(columns=df.columns[np.r_[1, 2, 101:117, 121:124, 126]])

import pandas pd
df = pd.DataFrame(np.random.randint(1, 10, (2, 130)))
df.drop(columns=df.columns[np.r_[1, 2, 101:117, 121:124, 126]])
#     0    3    4    5    6 ... 120 124 125  127
#0    6    1    3    7    2 ...   8   7   2    6
#1    1    9    2    5    3 ...   7   3   9    4
ALollz
  • 57,915
  • 7
  • 66
  • 89
0

This should work:

df.drop(df.columns[[indexes_of_columns_you_want_to_delete]], axis=1, inplace=True)

melowgs
  • 420
  • 1
  • 4
  • 13
0

Please try this:

import numpy as np
import pandas as pd
input_df.drop(input_df.columns[[np.r_[0,2:4]]],axis=1, inplace = True)
RenauV
  • 363
  • 2
  • 11