简体   繁体   English

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

[英]Replace all -1 in numpy array with values from another array

I have two numpy arrays, eg:我有两个 numpy 数组,例如:

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

I would like to replace all -1 in x with numbers in y , that are not in x .我想用y数字替换x所有-1 ,这些数字不在x First -1 with first number in y that is not in x ( 3 ), second -1 with second number in y that is not in x ( 5 ), ... So final x should be:第一个-1y中的第一个数字不在x ( 3 ) 中,第二个-1y中的第二个数字不在x ( 5 ) 中,......所以最终的x应该是:

[4 3 1 5 6 2]

I created this function:我创建了这个函数:

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

It's working, but I need run this function many times (eg milion times), so I would like to optimize it.它正在工作,但我需要多次运行此功能(例如百万次),因此我想对其进行优化。 Is there any way?有什么办法吗?

You could do:你可以这样做:

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)

Output输出

[4 3 1 5 6 2]
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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM