用另一个数组中的值替换numpy数组中的所有-1

时间:2019-11-22 18:50:51

标签: python arrays python-3.x numpy optimization

我有两个numpy数组,例如g。:

x = np.array([4, -1, 1, -1, -1, 2])
y = np.array([1, 2, 3, 4, 5, 6])

我想将-1中的所有x替换为y中的数字,而不是x中的数字。第一个-1的第一个数字y不在x3)中,第二个-1的第二个数字不在y中在x5)中,...所以最后的x应该是:

[4 3 1 5 6 2]

我创建了此函数:

import numpy as np
import time

start = time.time()

def fill(x, y):
    x_i = 0
    y_i = 0

    while x_i < len(x) and y_i < len(y):
        if x[x_i] != -1: # If current value in x is not -1.
            x_i += 1
            continue

        if y[y_i] in x: # If current value in y is already in x.
            y_i += 1
            continue

        x[x_i] = y[y_i] # Replace current -1 in x by current value in y.


for i in range(10000):
    x = np.array([4, -1, 1, -1, -1, 2])
    y = np.array([1, 2, 3, 4, 5, 6])
    fill(x, y)

end = time.time()
print(end - start) # 0.296

它正在工作,但是我需要多次运行此功能(例如,数百万次),因此我想对其进行优化。有什么办法吗?

2 个答案:

答案 0 :(得分:1)

您可以这样做:

import numpy as np

x = np.array([4, -1, 1, -1, -1, 2])
y = np.array([1, 2, 3, 4, 5, 6])

# create set of choices
sx = set(x)
choices = np.array([yi for yi in y if yi not in sx])

# assign new values
x[x == -1] = choices[:(x == -1).sum()]

print(x)

输出

[4 3 1 5 6 2]

答案 1 :(得分:1)

y_not_in_x = np.setdiff1d(y, x)
x_eq_neg1 = x == -1
n_neg1s = np.sum(x_eq_neg1)
x[x_eq_neg1] = y_not_in_x[:n_neg1s]