如何用numpy构造rank数组? (什么是秩数组?)

问题描述 投票:0回答:2

在我的Python课程中,我们正在学习如何使用Numpy,所以我们收到了一个关于它的作业。我的问题是:什么是rank数组以及如何使用python构建它?我的老师试图用这些台词解释这一点,但我实际上什么也不明白:( 这些是说明:

排名计算器(A) - 5 分

给定一个 numpy ndarray A,返回其排名数组。

Input: [[ 9 4 15 0 18]
        [16 19 8 10 1]]

Return value: [[4 2 6 0 8]
               [7 9 3 5 1]]

返回值应该是与原始数组大小和形状相同的ndarray

A

那么,有人可以解释一下吗?

python arrays numpy rank
2个回答
0
投票

您可以多次使用

numpy.argsort
来处理矩阵,如 this answer on SO 中所建议。

import numpy as np

inp = np.array([[9,4,15,0,18],
                [16,19,8,10,1]])

inp.ravel().argsort().argsort().reshape(inp.shape)
array([[4, 2, 6, 0, 8],
       [7, 9, 3, 5, 1]])

什么是秩矩阵?

总而言之,如果我要取出矩阵中的所有整数,并将它们从小到大排序,然后为每个整数分配从 0 到 9 的

rank
,这将得到排名矩阵。请注意,最小的是 0,其排名为 0,而最大的是 19,其排名最后为 9。

双参数排序如何工作

#printing them so they align nicely
print('Array ->', end='')
for i in inp.ravel().astype('str'):
    print(i.center(4), end='')
print('\n')
print('Sort1 ->', end='')
for i in inp.ravel().argsort().astype('str'):
    print(i.center(4), end='')
print('\n')
print('Sort2 ->', end='')
for i in inp.ravel().argsort().argsort().astype('str'):
    print(i.center(4), end='')
Array -> 9   4   15  0   18  16  19  8   10  1  

Sort1 -> 3   9   1   7   0   8   2   5   4   6  

Sort2 -> 4   2   6   0   8   7   9   3   5   1  

我们先来总结一下

argsort
的作用。 它获取每个元素的位置,并在排序后将它们放在它们所属的位置。知道了这一点,我们就可以编写一个本质上是三角形的后向逻辑。让我们从 sort2 开始,然后是 sort1,然后是 array。

  1. 0th
    (在排序2中)是
    4th
    (在排序1中),
    4th
    (在排序1中)是
    0th
    (在数组中)。所以
    0th
    (在数组中)是
    0th
    (在 sort2 中)

  2. 9th
    (在排序2中)是
    1st
    (在排序1中),
    1st
    (在排序1中)是
    9th
    (在数组中)。所以,
    9th
    (在数组中)是
    9th
    (在排序2中)

  3. 6th
    (在排序2中)是
    9th
    (在排序1中),
    9th
    (在排序1中)是
    6th
    (在数组中)。所以,
    6th
    (在数组中)是
    6th
    (在排序2中)

理解它有点令人困惑,但是一旦你理解了 argsort() 的工作原理,你就不会有问题了。


0
投票

问)什么是秩数组?

Ans:基本上是按排序顺序排列的元素。

基本上,你的老师要求你的是返回每个元素的位置(如果它们按升序排序)。

代码:

import numpy as np

A = np.array([[9, 4, 15, 0, 18],
              [16, 19, 8, 10, 1]])

flatA = A.flatten()
sorted_flatA = sorted(flatA)  # will become -> [0, 1, 4, 8, 9, 10, 15, 16, 18, 19]

# Using a 'MAP' to map the values of sorted_faltA to the index of sorted_faltA.
MAP = {}
for i in range(len(sorted_flatA)):
    MAP[sorted_flatA[i]] = i

# Then simply going through the 2D array snd replacing the with their ranks.
res = np.zeros(A.shape)
for i in range(A.shape[0]):
    for j in range(A.shape[1]):
        res[i][j] = MAP[A[i][j]]

print(res)
© www.soinside.com 2019 - 2024. All rights reserved.