Pandas 使用切片和整数索引选择列

Che*_*eng 1 python indexing slice dataframe pandas

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

df3.iloc[:, [2, 4:]]
Run Code Online (Sandbox Code Playgroud)

文件“”,第 1 行
df3.iloc[:, [2, 4:]]
___________^
语法错误:语法无效

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

还有其他快速方法可以做到这一点吗?

jez*_*ael 5

您可以range使用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
Run Code Online (Sandbox Code Playgroud)

另一个解决方案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
Run Code Online (Sandbox Code Playgroud)