如何使用numpy对数组和矩阵进行排序 [英] How to sort an array and a matrix together using numpy
问题描述
我有一个数组y
和一个矩阵X
,它是CSR稀疏的.
I have an array y
and a matrix X
that is CSR sparse.
我需要对y
和X进行随机排序,其中y
的每一行都对应X
中的一行.
I need to do a random sort of y
and X where each row of y
corresponds to a row in X
.
使用NumPy,我该怎么做?
Using NumPy, how do I do that?
推荐答案
为了获得随机排序,可以尝试使用np.random.shuffle
函数.
In order to get a random sort, you could try to use the np.random.shuffle
function.
# Create an array of indices
indices = np.arange(y.size)
# Randomize it
np.random.shuffle(indices)
您现在可以使用indices
通过花式索引y_new = y[indices]
将y
随机化.
You can now use indices
to randomize y
with fancy indexing y_new = y[indices]
.
您可以使用相同的indices
重新排序矩阵,但请注意,CSR矩阵不支持奇特索引.您必须将其转换为LIL,对其重新排序,然后再将其转换为CSR.
You could use the same indices
to reorder your matrix, but be careful, CSR matrices don't support fancy indexing. You'll have to transform it to LIL, reorder it, then retransform it to CSR.
这篇关于如何使用numpy对数组和矩阵进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!