Python:比较并插入有序numpy数组的向量

时间:2019-03-09 04:22:45

标签: python broadcast numpy-broadcasting

我有一个numpy数组,其行是有序的,并且是一个向量。如果向量的值小于每个数组行的某些值,则需要将该向量插入到数组中。此外,我需要获取位置的索引。我可以使用类似矢量的向量而不是两个for循环吗?

例如,数组的第i行为[1,3,5,6],向量的i值为4,结果为([1,3,4,5], 2)。 这是代码示例。

import random
import numpy as np

random.seed(0)
num_query = 2
topk = 3

distance = np.Inf * np.ones((num_query, topk))

print(distance)

for iter in range(4):
    print('------------loop: {:d}------------'.format(iter))
    dist = np.random.randn(num_query) / (0.3 * (iter+1))
    dist = dist * np.sign(dist)
    rows, columns = distance.shape
    for row in range(rows):
        d = dist[row]
        if d > distance[row, columns - 1]:
            continue
        min_col = 0
        for column in range(columns-1, -1, -1):
            if distance[row, column] < d:
                min_col = column + 1
                break
        distance[row, min_col + 1:] = distance[row, min_col:-1]
        distance[row, min_col] = d
    print(dist)
    print(distance)
    print('+++++++++++++++++++++++++++++++')
print(distance)

输出为:

[[inf inf inf]
 [inf inf inf]]
------------loop: 0------------
[3.60155727 0.0991411 ]
[[3.60155727        inf        inf]
 [0.0991411         inf        inf]]
+++++++++++++++++++++++++++++++
------------loop: 1------------
[1.4839764  1.99641269]
[[1.4839764  3.60155727        inf]
 [0.0991411  1.99641269        inf]]
+++++++++++++++++++++++++++++++
------------loop: 2------------
[2.44132044 0.19221564]
[[1.4839764  2.44132044 3.60155727]
 [0.0991411  0.19221564 1.99641269]]
+++++++++++++++++++++++++++++++
------------loop: 3------------
[0.29206705 1.17013653]
[[0.29206705 1.4839764  2.44132044]
 [0.0991411  0.19221564 1.17013653]]
+++++++++++++++++++++++++++++++
[[0.29206705 1.4839764  2.44132044]
 [0.0991411  0.19221564 1.17013653]]

0 个答案:

没有答案