Chr*_*ris 11 python numpy pandas
我有一个120,000*4的numpy数组,如下所示.每行都是一个样本.第一列是秒的时间,或index使用Pandas术语.
0.014 14.175 -29.97 -22.68
0.022 13.905 -29.835 -22.68
0.030 12.257 -29.32 -22.67
... ...
1259.980 -0.405 2.205 3.825
1259.991 -0.495 2.115 3.735
Run Code Online (Sandbox Code Playgroud)
我想选择记录在100.000到200.000秒之间的行并将其保存到新数组中.如果这是一个Pandas数据帧,我会写df.loc[100:200].numpy中的等效操作是什么?
这不是可行性问题.我只是想知道是否有任何pythonic单行解决方案.
假设索引已排序:
IIUC,
x=np.array([ [1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]])
x[(x[:,0] >= 5) & (x[:,0] <= 9) ]
Run Code Online (Sandbox Code Playgroud)
所以你会有100和200而不是5和9.
有关更一般的解决方案,请查看Wen的答案
来自Raf的数据
x[np.where(x[:,0]==5)[0][0]:np.where(x[:,0]==9)[0][0]+1,:]
Out[341]:
array([[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
Run Code Online (Sandbox Code Playgroud)
注意
只有使用大于和小于不能完全替换的.loc,.loc的后端是索引位置而不是值范围
例如
df
Out[348]:
0 1 2 3
0 1 2 3 4
1 5 6 7 8
4444 9 10 11 12
3 13 14 15 16
df.loc[1:3]
Out[347]:
0 1 2 3
1 5 6 7 8
4444 9 10 11 12
3 13 14 15 16
Run Code Online (Sandbox Code Playgroud)