1

Say I want to delete a set of adjacent columns in a DataFrame and my code looks something like this currently:

del df['1'], df['2'], df['3'], df['4'], df['5'], df['6']

This works, but I was wondering if there was a more efficient, compact, or aesthetically pleasing way to do it, such as:

del df['1','6']
Romulus3799
  • 1,827
  • 3
  • 15
  • 20
  • I reopen question because there is no necessary use only `drop`, there is used some logic with `range` or `np.arange` – jezrael Feb 08 '17 at 15:05

2 Answers2

0

I think you need drop, for selecting is used range or numpy.arange:

df = pd.DataFrame({'1':[1,2,3],
                   '2':[4,5,6],
                   '3':[7,8,9],
                   '4':[1,3,5],
                   '5':[7,8,9],
                   '6':[1,3,5],
                   '7':[5,3,6],
                   '8':[5,3,6],
                   '9':[7,4,3]})

print (df)
   1  2  3  4  5  6  7  8  9
0  1  4  7  1  7  1  5  5  7
1  2  5  8  3  8  3  3  3  4
2  3  6  9  5  9  5  6  6  3

print (np.arange(1,7))
[1 2 3 4 5 6]

print (range(1,7))
range(1, 7)

#convert string column names to int
df.columns = df.columns.astype(int)
df = df.drop(np.arange(1,7), axis=1)
#another solution with range
#df = df.drop(range(1,7), axis=1)
print (df)
   7  8  9
0  5  5  7
1  3  3  4
2  6  6  3
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
0

You can do this without modifying the columns, by passing a slice object to drop:

In [29]:
df.drop(df.columns[slice(df.columns.tolist().index('1'),df.columns.tolist().index('6')+1)], axis=1)

Out[29]:
       7  8  9
    0  5  5  7
    1  3  3  4
    2  6  6  3

So this returns the ordinal position of the lower and upper bound of the column end points and passes these to create a slice object against the columns array

EdChum
  • 376,765
  • 198
  • 813
  • 562