我使用较小的数组和较少的索引来执行此操作,以便我可以轻松地检查结果,但它应该转化为您的用例。我认为这个解决方案非常有效,因为一切都已到位。
import numpy as np
x = np.random.randint(10, size=(12,3))
indices = np.array([5,7,9])
# Swap top 3 rows with the rows 5,7,9 and vice versa
x[:len(indices)], x[indices] = x[indices], x[:len(indices)].copy()
# Sort the wanted portion of array
x[len(indices):].sort(axis=0)
这是输出:
>>> import numpy as np
>>> x = np.random.randint(10, size=(10,3))
>>> indices = np.array([5,7,9])
>>> x
array([[7, 1, 8],
[7, 4, 6],
[6, 5, 2],
[6, 8, 4],
[2, 0, 2],
[3, 0, 4], # 5th row
[4, 7, 4],
[3, 1, 1], # 7th row
[3, 5, 3],
[0, 5, 9]]) # 9th row
>>> # We want top of array to be
>>> x[indices]
array([[3, 0, 4],
[3, 1, 1],
[0, 5, 9]])
>>> # Swap top 3 rows with the rows 5,7,9 and vice versa
>>> x[:len(indices)], x[indices] = x[indices], x[:len(indices)].copy()
>>> # Assert that rows have been swapped correctly
>>> x
array([[3, 0, 4], #
[3, 1, 1], # Top of array looks like above
[0, 5, 9], #
[6, 8, 4],
[2, 0, 2],
[7, 1, 8], # Previous top row
[4, 7, 4],
[7, 4, 6], # Previous second row
[3, 5, 3],
[6, 5, 2]]) # Previous third row
>>> # Sort the wanted portion of array
>>> x[len(indices):].sort(axis=0)
>>> x
array([[3, 0, 4], #
[3, 1, 1], # Top is the same, below is sorted
[0, 5, 9], #
[2, 0, 2],
[3, 1, 2],
[4, 4, 3],
[6, 5, 4],
[6, 5, 4],
[7, 7, 6],
[7, 8, 8]])
编辑:
如果indices 中的任何元素小于len(indices),则此版本应处理
import numpy as np
x = np.random.randint(10, size=(12,3))
indices = np.array([1,2,4])
tmp = x[indices]
# Here I just assume that there aren't any values less or equal to -1. If you use
# float, you can use -np.inf, but there is no such equivalent for ints (which I
# use in my example).
x[indices] = -1
# The -1 will create dummy rows that will get sorted to be on top of the array,
# which can switch with tmp later
x.sort(axis=0)
x[indices] = tmp