Pandas select 列使用切片和整数索引

Pandas select columns using slicing and integer index

我正在尝试 select 第 2 列和第 4 列:(第 4 列直到最后):

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

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

我显然收到一条错误消息。第 4 列之后有很多列,所以写这样的东西感觉不对:[2, 4, 5, 6, 7, ...]

还有其他快速方法吗?

您可以将 rangeshape 一起使用:

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

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