Python 选择除numpy数组范围内的行以外的所有行
我有一个矩阵,我想迭代它的各个部分。每一次迭代我都想抓住那个块,而不是那个块中的所有东西。比如说Python 选择除numpy数组范围内的行以外的所有行,python,arrays,numpy,indexing,Python,Arrays,Numpy,Indexing,我有一个矩阵,我想迭代它的各个部分。每一次迭代我都想抓住那个块,而不是那个块中的所有东西。比如说 #grab all rows between index1 and index2 chunk = arr[index1:index2, :] #want to grab the rest of the matrix that wasn't already grabbed in chunk #this is the wrong syntax but demonstrates the behavior
#grab all rows between index1 and index2
chunk = arr[index1:index2, :]
#want to grab the rest of the matrix that wasn't already grabbed in chunk
#this is the wrong syntax but demonstrates the behavior I'm looking for
rest = arr[ not(index1:index2), :]
有什么好办法吗?如果你知道你不想要index1:index2。。为什么不这样做呢
rest=arr[index3:]
一种方法是
vstack
2件:
In [68]: arr
Out[68]:
array([[ 0, 5, 10, 15],
[ 1, 6, 11, 16],
[ 2, 7, 12, 17],
[ 3, 8, 13, 18],
[ 4, 9, 14, 19]])
In [69]: arr[2:4,:]
Out[69]:
array([[ 2, 7, 12, 17],
[ 3, 8, 13, 18]])
In [70]: np.vstack([arr[:2,:],arr[4:,:]])
Out[70]:
array([[ 0, 5, 10, 15],
[ 1, 6, 11, 16],
[ 4, 9, 14, 19]])
或者您可以构建一个不连续的索引列表,例如[0,1,4]
arr[[0,1,4],:]
在np.lib.index\u技巧中
有一个函数(实际上是类),它简化了构造这样一个列表(从列表或切片)的过程:
事实上,r
可以像vstack
一样使用:
np.r_[arr[:2,:],arr[4:,:]]
通常,您希望根据某些条件分割数组,在这种情况下,布尔索引非常有用:
I=np.ones(5,dtype=bool)
I[2:4]=False # array True, with False for the rows to omit
arr[I,:]
arr[~I,:] # the original slice
首先,这个解决方案假设我抓取的块最初从矩阵的开头开始。然而,就你的观点而言,我想我可以做一些类似于
rest=arr[:index1]+arr[index2:][/code>…这可能是最好的解决方案。我只是想知道是否有一个更简洁的方法,我想这可能是你最好的选择。我很想知道是否有更好的方法:)
I=np.ones(5,dtype=bool)
I[2:4]=False # array True, with False for the rows to omit
arr[I,:]
arr[~I,:] # the original slice