简体   繁体   English

选择除numpy数组范围内的所有行

[英]Selecting all rows but those within a range of a numpy array

I have a matrix and I want to iterate over chunks of it. 我有一个矩阵,我想遍历它的大部分。 Each iteration I want to grab that chunk and everything NOT in that chunk. 每次迭代我都想抓住那个块,而不是那个块中的所有东西。 For example 例如

#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), :] 

Any good way to do this? 有什么好办法吗?

One approach is to vstack the 2 pieces: 一种方法是vstack这两个部分:

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]])

Or you could construct a discontinuous list of indices, eg [0,1,4] 或者,您可以构造不连续的索引列表,例如[0,1,4]

arr[[0,1,4],:]

In np.lib.index_tricks there is a function (class actually) that streamlines constructing such a list (from lists or slices): np.lib.index_tricks有一个函数(实际上是类)可以简化构造列表(从列表或切片)的过程:

np.r_[:2,4:5]  # == np.array([0,1,4])

In fact r_ can be used like vstack : 实际上r_可以像vstack一样vstack

np.r_[arr[:2,:],arr[4:,:]]

Often you want to divide an array based on some condition, in which case a boolean index is useful: 通常,您想根据某种条件划分数组,在这种情况下,布尔索引很有用:

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

如果您知道不想要index1:index2 ..为什么不这样做呢?

rest=arr[index3:]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM