use*_*995 3 python r dataframe pandas
我想使用列索引从pandas dataframe特定列中进行选择。
特别是,我想通过c(12:26,69:85,96:99,134:928,933:935,940:967)
R中生成的列索引选择列索引。我想知道如何在Python中做到这一点?
我在想类似以下的内容,但是python当然没有名为c()的函数。
input2 = input2.iloc[:,c(12:26,69:85,96:99,134:928,933:935,940:967)]
Run Code Online (Sandbox Code Playgroud)
将@hrbrmstr的注释放入答案中,因为它解决了我的问题,并且我想清楚地说明此问题已解决。另外,请注意,范围(a,b)给出数字(a,a + 1,...,b-2,b-1),但不包括b。
R的合并功能
c(4,12:26,69:85,96:99,134:928,933:935)
Run Code Online (Sandbox Code Playgroud)
被翻译成Python
[4] + list(range(12,27)) + list(range(69,86)) + list(range(96,100)) + list(range(134,929)) + list(range(933,936))
Run Code Online (Sandbox Code Playgroud)
The equivalent is numpy's r_
. It combines integer slices without needing to call ranges for each of them:
np.r_[2:4, 7:11, 21:25]
Out: array([ 2, 3, 7, 8, 9, 10, 21, 22, 23, 24])
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)