我想使用列索引从 Pandas 数据框中选择特定的列。
特别是,我想通过 R 中的 c(12:26,69:85,96:99,134:928,933:935,940:967)
生成的列索引来选择列索引。我想知道如何在 Python 中做到这一点?
我在想类似下面的事情,但是当然,python 没有一个叫做 c() 的函数...
input2 = input2.iloc[:,c(12:26,69:85,96:99,134:928,933:935,940:967)]
最佳答案
等同于 numpy 的 r_
.它结合整数切片而不需要为每个切片调用范围:
np.r_[2:4, 7:11, 21:25]
Out: array([ 2, 3, 7, 8, 9, 10, 21, 22, 23, 24])
df = pd.DataFrame(np.random.randn(1000))
df.iloc[np.r_[2:4, 7:11, 21:25]]
Out:
0
2 2.720383
3 0.656391
7 -0.581855
8 0.047612
9 1.416250
10 0.206395
21 -1.519904
22 0.681153
23 -1.208401
24 -0.358545
关于Python 等效于 R c() 函数,用于数据框列索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32443778/