[英]How to label the entries of a matrix as their indices but still keep their original numerical values?
I have a matrix_1 full of numerical values and what I'd like to do is transform this into a matrix_2 with the values(of matrix_1 sorted) and then replace these sorted values in matrix 2 with the original indices from matrix_1.我有一个充满数值的matrix_1,我想做的是将其转换为matrix_2,其值(对matrix_1 排序),然后用matrix_1 中的原始索引替换矩阵2 中的这些排序值。
I don't want to use any loops as the matrices are rather large.我不想使用任何循环,因为矩阵相当大。
for example : matrix_1=[[2,3,4,1],[6,5,9,7]]
I want to end up with matrix_2=[[(1,4),(1,1),(1,2),(1,3)],
[(2,2),(2,1),(2,4),(2,3)]]
I've tried use np.ndenumerate on the original matrix but it returns array([numpy.ndenumerate object at 0x1a1a9fce90], dtype=object)我试过在原始矩阵上使用 np.ndenumerate 但它返回数组([numpy.ndenumerate object at 0x1a1a9fce90], dtype=object)
I've now also tried np.argsort() but it doesn't seem to work, possibly because all of my entries are floats...我现在也尝试过 np.argsort() 但它似乎不起作用,可能是因为我所有的条目都是浮点数......
using np.argsort should do the trick:使用 np.argsort 应该可以解决问题:
matrix_1=np.array([[2,3,4,1],[6,5,9,7]])
matrix_1
array([[2, 3, 4, 1],
[6, 5, 9, 7]])
x = np.argsort(matrix_1,axis=1)
array([[3, 0, 1, 2],
[1, 0, 3, 2]], dtype=int64)
A matrix consisting of floats shouldn't pose a problem.由浮点数组成的矩阵不应该造成问题。
You can then create the list as:然后,您可以将列表创建为:
[[(i+1,v+1) for v in enumerate(y)] for i, y in enumerate(x.tolist())]
[[(1, 4), (1, 1), (1, 2), (1, 3)], [(2, 2), (2, 1), (2, 4), (2, 3)]]
You must come from R or other language that start indexing on 1
.您必须来自 R 或其他从
1
开始索引的语言。 In Python, indexes start at 0
, so you have to explicitly add + 1
to the indexes to make them start at 1.在 Python 中,索引从
0
开始,因此您必须将+ 1
显式添加到索引以使其从 1 开始。
Use argsort
and then reshape
使用
argsort
然后reshape
m1 = matrix_1.argsort(1) + 1
i = (np.repeat(np.arange(m1.shape[0]), m1.shape[1]) + 1).reshape(m1.shape)
np.concatenate([m1[:, None],i[:, None]], axis=1).swapaxes(2,1)
which outputs哪个输出
array([[[4, 1],
[1, 1],
[2, 1],
[3, 1]],
[[2, 2],
[1, 2],
[4, 2],
[3, 2]]])
argsort
applied to the flattened array: argsort
应用于展平数组:
In [110]: np.argsort(arr1.ravel())
Out[110]: array([3, 0, 1, 2, 5, 4, 7, 6])
Turn that into 2d indices:将其转换为 2d 索引:
In [111]: np.unravel_index(_,(2,4))
Out[111]: (array([0, 0, 0, 0, 1, 1, 1, 1]), array([3, 0, 1, 2, 1, 0, 3, 2]))
Combine the arrays into one, and reshape:将 arrays 合二为一,重塑:
In [112]: np.transpose(_)
Out[112]:
array([[0, 3],
[0, 0],
[0, 1],
[0, 2],
[1, 1],
[1, 0],
[1, 3],
[1, 2]])
In [113]: _+1 # tweak values to match yours
Out[113]:
array([[1, 4],
[1, 1],
[1, 2],
[1, 3],
[2, 2],
[2, 1],
[2, 4],
[2, 3]])
In [114]: _.reshape(2,4,2)
Out[114]:
array([[[1, 4],
[1, 1],
[1, 2],
[1, 3]],
[[2, 2],
[2, 1],
[2, 4],
[2, 3]]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.