[英]Numpy sorting array (sparse)
I'm trying to work out why this code doesn't sort the array... 我试图弄清楚为什么这段代码不对数组排序...
x = array([[3, 2, 4, 5, 7, 4, 3, 4, 3, 3, 1, 4, 6, 3, 2, 4, 3, 2]])
xCoo = sps.coo_matrix(x)
perm = np.argsort(x)
xCoo.col = perm[xCoo.col]
print(xCoo.toarray()) # array([3, 2, 4, 5, 7, 4, 3, 4, 3, 3, 1, 4, 6, 3, 2, 4, 3, 2])
I'm not sure what I've misunderstood. 我不确定我误会了什么。 What's the correct way to do this?
正确的方法是什么?
Thank you. 谢谢。
PS I'm aware that I can just call sort on the array; PS,我知道我可以在数组上调用sort。 however, I went to apply this same permutation over and over again.
但是,我又一次又一次地应用了相同的排列。
The first complication is the np.argsort(x)
returns a 2d array. 第一个复杂之处是
np.argsort(x)
返回2d数组。 Lets do the sort on flattened x
to get a simpler 1d perm
: 让我们对展平的
x
进行排序以获得更简单的1d perm
:
In [1118]: perm=np.argsort(x,None)
In [1119]: perm
Out[1119]:
array([10, 17, 1, 14, 13, 9, 16, 0, 6, 8, 5, 11, 2, 15, 7, 3, 12,
4], dtype=int32)
this sorts x
as we expect, right? 就像我们期望的那样对
x
排序,对不对?
In [1120]: x[:,perm]
Out[1120]: array([[1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 6, 7]])
now apply it in the same way to xCoo
, except we have to convert it to lil
format. 现在将其以相同的方式应用于
xCoo
,除了我们必须将其转换为lil
格式。 coo
format isn't subscriptable: coo
格式不可下标:
In [1121]: xCoo.tolil()[:,perm].A
Out[1121]: array([[1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 6, 7]], dtype=int32)
To apply perm
directly to the attributes of xCoo
, we need to do another sort: 要将
perm
直接应用于xCoo
的属性,我们需要执行另一种排序:
xCoo.col = np.argsort(perm)[xCoo.col] # <====
This works for multirow xCoo
with zeros. 这适用于带有零的多行
xCoo
。
You can also sort the data: 您还可以对数据进行排序:
xCoo.data = xCoo.data[perm[xCoo.col]]
These work here, but they need more testing. 这些在这里有效,但是需要更多测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.