假设我有一个二维NumPy数组:
x = np.random.rand(100, 100000)
我检索出按列排序的索引(即每列都独立排序,返回索引):
idx = np.argsort(x, axis=0)
然后,对于每一列,我需要从索引为[10, 20, 30, 40, 50]的值开始,将前5行(该列的前五行)放在最前面,然后跟随其余已排序的值(不是索引!)。
一个天真的方法可能是:
indices = np.array([10, 20, 30, 40, 50])
out = np.empty(x.shape, dtype=int64)
for col in range(x.shape[1]):
# For each column, fill the first few rows with `indices`
out[:indices.shape[0], col] = x[indices, col] # Note that we want the values, not the indices
# Then fill the rest of the rows in this column with the remaining sorted values excluding `indices`
n = indices.shape[0]
for row in range(indices.shape[0], x.shape[0]):
if idx[row, col] not in indices:
out[n, col] = x[row, col] # Again, note that we want the value, not the index
n += 1
out
的大小都相同。创建一个具有适当大小的out
数组,然后将x [indices]
和p2
复制到其中,是否会更“好”或更有效?这样,我就可以避免昂贵的内存创建了。 - slaw方法 #2-备选
是否适合你。我会相应地编辑方法 #1
。 - Divakarnp.vstack
!我想,从技术上讲,我们可以只做out[n:] = np.take_along_axis(...)
并且可能在迭代中重复使用mask
。我将阅读关于take_long_axis
的内容,以便理解其中的情况。 - slaw