考虑数组a
np.random.seed([3,1415])
a = np.random.randint(10, size=(5, 4))
a
array([[0, 2, 7, 3],
[8, 7, 0, 6],
[8, 6, 0, 2],
[0, 4, 9, 7],
[3, 2, 4, 3]])
我可以创造b
其中包含对每列进行排序的排列。
b = a.argsort(0)
b
array([[0, 0, 1, 2],
[3, 4, 2, 0],
[4, 3, 4, 4],
[1, 2, 0, 1],
[2, 1, 3, 3]])
我可以排序a
with b
a[b, np.arange(a.shape[1])[None, :]]
array([[0, 2, 0, 2],
[0, 2, 0, 3],
[3, 4, 4, 3],
[8, 6, 7, 6],
[8, 7, 9, 7]])
这是说明我正在寻找的输出的底漆。我想要一个数组b
具有对相应列进行排序所需的排列a
当还考虑lexsort
与另一个数组。
np.random.seed([3,1415])
a = np.random.randint(10, size=(10, 4))
g = np.random.choice(list('abc'), 10)
a
array([[0, 2, 7, 3],
[8, 7, 0, 6],
[8, 6, 0, 2],
[0, 4, 9, 7],
[3, 2, 4, 3],
[3, 6, 7, 7],
[4, 5, 3, 7],
[5, 9, 8, 7],
[6, 4, 7, 6],
[2, 6, 6, 5]])
g
array(['c', 'a', 'c', 'b', 'a', 'a', 'a', 'b', 'c', 'b'],
dtype='<U1')
我想生成一个数组b
其中每一列都是必要的排列lexsort
对应的列a
。还有lexsort
首先按定义的组对列进行排序g
然后通过每列中的值a
.
我可以通过以下方式生成结果:
r = np.column_stack([np.lexsort([a[:, i], g]) for i in range(a.shape[1])])
r
array([[4, 4, 1, 4],
[5, 6, 6, 1],
[6, 5, 4, 5],
[1, 1, 5, 6],
[3, 3, 9, 9],
[9, 9, 7, 3],
[7, 7, 3, 7],
[0, 0, 2, 2],
[8, 8, 0, 0],
[2, 2, 8, 8]])
我们可以看到这是有效的
g[r]
array([['a', 'a', 'a', 'a'],
['a', 'a', 'a', 'a'],
['a', 'a', 'a', 'a'],
['a', 'a', 'a', 'a'],
['b', 'b', 'b', 'b'],
['b', 'b', 'b', 'b'],
['b', 'b', 'b', 'b'],
['c', 'c', 'c', 'c'],
['c', 'c', 'c', 'c'],
['c', 'c', 'c', 'c']],
dtype='<U1')
and
a[r, np.arange(a.shape[1])[None, :]]
array([[3, 2, 0, 3],
[3, 5, 3, 6],
[4, 6, 4, 7],
[8, 7, 7, 7],
[0, 4, 6, 5],
[2, 6, 8, 7],
[5, 9, 9, 7],
[0, 2, 0, 2],
[6, 4, 7, 3],
[8, 6, 7, 6]])
Question
有没有办法“广播”分组数组的使用g
用于每列lexsort
?什么是更有效的方法来做到这一点?