Cheng
Cheng

Reputation: 17904

Pandas select columns using slicing and integer index

I am trying to select columns 2 and 4: (column 4 till the end):

df3.iloc[:, [2, 4:]]

File "", line 1
df3.iloc[:, [2, 4:]]
___________^
SyntaxError: invalid syntax

I get an error message obviously. There are many columns after col 4 so writing something like this does not feel right: [2, 4, 5, 6, 7, ...]

Is there any other quick way of doing this?

Upvotes: 1

Views: 3215

Answers (1)

jezrael
jezrael

Reputation: 862731

You can use range with shape:

df3 = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9],
                   'D':[1,3,5],
                   'E':[5,3,6],
                   'F':[7,4,3]})

print (df3)
   A  B  C  D  E  F
0  1  4  7  1  5  7
1  2  5  8  3  3  4
2  3  6  9  5  6  3

cols = ([2] + list(range(4,df3.shape[1])))
print (cols)
[2, 4, 5]

print (df3.iloc[:,cols])
   C  E  F
0  7  5  7
1  8  3  4
2  9  6  3

Another solution with numpy.r_:

cols1 = np.r_[2, np.arange(4,df3.shape[1])]
print (cols1)
[2 4 5]

print (df3.iloc[:,cols1])
   C  E  F
0  7  5  7
1  8  3  4
2  9  6  3

Upvotes: 5

Related Questions