如何获取 2D 数组每行中的 8 个最大值/最高值及其索引

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

我正在编写 Python 脚本。我试图在 Python 中获得 8 个最高值及其各自的 2D 数组每一行的索引的列表。我的数组的形状有 4148 行和 167 列。我本质上想要的是,对于每一行,它应该给我该行中存在的 8 个最高值(按降序排列)及其索引。

我对 Python 比较陌生,我尝试在下面实现这个,但是它为我提供了整个数组中的 8 个最大值及其索引。

a = predicting[:]
indices =  np.argpartition(a.flatten(), -8)[-8:]
np.vstack(np.unravel_index(indices, a.shape)).T
python arrays list numpy sorting
3个回答
1
投票

你可以参考我的例子。您将得到一个包含 8 个最大数字索引的 2D 序列和一个包含 8 个最大数字的 2D 序列。:

a = np.random.randint(0,12,size=(12,12))
indice =  np.argsort(-a)
indice = indice[:,:8]
b = np.sort(-a.copy())*-1
maximum_8 = b[:,:8]

一个输出: 一个

array([[ 1, 10, 11,  8,  8,  2,  4, 11,  2,  5,  3,  6],
   [11,  2,  2,  7,  3,  3,  9,  0,  0,  0, 10,  4],
   [ 8, 10,  8, 10,  5,  9,  6,  7,  3,  5,  2,  8],
   [ 4,  8,  8,  2,  6,  2,  0,  7,  1, 10, 10,  6],
   [ 9,  1,  5,  0,  6,  4,  3,  6,  7,  0,  7,  7],
   [ 3,  7,  8,  0, 11, 10, 10,  8,  2,  7,  2,  7],
   [ 6,  7,  5, 11,  6,  5,  4,  3,  0,  0,  8,  2],
   [ 7, 11,  7,  9, 11, 11,  8, 11,  4, 11,  6, 11],
   [11,  3,  9,  7, 11,  8, 11,  3,  8,  9,  0,  3],
   [ 4,  7,  6,  9, 11,  3,  8,  0,  5, 11,  6,  5],
   [ 9, 11,  8,  2,  5,  4,  4,  4,  9,  4,  7,  9],
   [ 5,  5,  3,  6,  4,  8,  4,  9,  4,  1,  8,  9]])

指数

array([[ 2,  7,  1,  3,  4, 11,  9,  6],
   [ 0, 10,  6,  3, 11,  4,  5,  1],
   [ 1,  3,  5,  0,  2, 11,  7,  6],
   [ 9, 10,  1,  2,  7,  4, 11,  0],
   [ 0,  8, 10, 11,  4,  7,  2,  5],
   [ 4,  5,  6,  2,  7,  1,  9, 11],
   [ 3, 10,  1,  0,  4,  2,  5,  6],
   [ 1,  4,  5,  7,  9, 11,  3,  6],
   [ 0,  4,  6,  2,  9,  5,  8,  3],
   [ 4,  9,  3,  6,  1,  2, 10,  8],
   [ 1,  0,  8, 11,  2, 10,  4,  5],
   [ 7, 11,  5, 10,  3,  0,  1,  4]], dtype=int64)

最大_8

array([[11, 11, 10,  8,  8,  6,  5,  4],
   [11, 10,  9,  7,  4,  3,  3,  2],
   [10, 10,  9,  8,  8,  8,  7,  6],
   [10, 10,  8,  8,  7,  6,  6,  4],
   [ 9,  7,  7,  7,  6,  6,  5,  4],
   [11, 10, 10,  8,  8,  7,  7,  7],
   [11,  8,  7,  6,  6,  5,  5,  4],
   [11, 11, 11, 11, 11, 11,  9,  8],
   [11, 11, 11,  9,  9,  8,  8,  7],
   [11, 11,  9,  8,  7,  6,  6,  5],
   [11,  9,  9,  9,  8,  7,  5,  4],
   [ 9,  9,  8,  8,  6,  5,  5,  4]])

0
投票

另一种可能的解决方案:

b = np.flip(np.argsort(a, axis=1)[:,-8:], axis=1)
v = np.take_along_axis(a, b, axis=1)

v, b # v = values; b = indices

0
投票

如果可以将行数据放入字典中,交换键和值并将其放入列表中,然后反向排序。然后为每行取列表的前 8 个值。

# put the row data in a dictionary called dictionaryRow, swap key and value and put into a list, sort in reverse)

x = sorted( [ (value, key) for key, value in dictionaryRow.items() ] ), reverse=True)
# Take the top 8 from the list
x[:8]
© www.soinside.com 2019 - 2024. All rights reserved.