繁体   English   中英

Python:根据掩码将列插入 numpy 数组

[英]Python: Insert columns into a numpy array based on mask

假设我有以下数据:

mask = [[0, 1, 1, 0, 1]] # 2D mask
ip_array = [[4, 5, 2]
            [3, 2, 1]
            [1, 8, 6]] # 2D array

我想在掩码中有 0 的地方将 0 列插入ip_array中。 所以 output 应该是这样的:

[[0, 4, 5, 0, 2]
 [0, 3, 2, 0, 1]
 [0, 1, 8, 0, 6]]

我是 numpy 功能的新手,我正在寻找一种有效的方法来做到这一点。 任何帮助表示赞赏!

这是分两步完成的一种方法:

(i) 创建一个正确形状的零数组( ip_array的第一维和mask的第二维)

(ii) 在第二维上使用mask (作为 boolean 掩码)并将ip_array的值分配给零数组。

out = np.zeros((ip_array.shape[0], mask.shape[1])).astype(int)
out[..., mask[0].astype(bool)] = ip_array
print(out)

Output:

[[0 4 5 0 2]
 [0 3 2 0 1]
 [0 1 8 0 6]]

带有参数和其他方法的解决方案,而不是绿色检查。 所以比较好理解。 只是最后一行对操作很重要。

import numpy
import random

n1 = 5
n2 = 5
r = 0.7
random.seed(1)
a = numpy.array([[0 if random.random() > r else 1 for _ in range(n1)]])
n3 = numpy.count_nonzero(a)
b = numpy.array([[random.randint(1,9) for _ in range(n3)] for _ in range(n2)])
c = numpy.zeros((n2, n1))
c[:, numpy.where(a)[1]] = b[:]

结果:

a = array([[1, 0, 0, 1, 1]])
b = array([[8, 8, 7],
       [4, 2, 8],
       [1, 7, 7],
       [1, 8, 5],
       [4, 2, 6]])
c = array([[8., 0., 0., 8., 7.],
       [4., 0., 0., 2., 8.],
       [1., 0., 0., 7., 7.],
       [1., 0., 0., 8., 5.],
       [4., 0., 0., 2., 6.]])

在这里,您的时间处理取决于 n 值:

在此处输入图像描述

使用此代码:

import numpy
import random
import time
import matplotlib.pyplot as plt

n1 = 5
n2 = 5
r = 0.7


def main(n1, n2):
    print()
    print(f"{n1 = }")
    print(f"{n2 = }")
    random.seed(1)
    a = numpy.array([[0 if random.random() > r else 1 for _ in range(n1)]])
    n3 = numpy.count_nonzero(a)
    b = numpy.array([[random.randint(1,9) for _ in range(n3)] for _ in range(n2)])
    t0 = time.time()
    c = numpy.zeros((n2, n1))
    c[:, numpy.where(a)[1]] = b[:]
    t = time.time() - t0
    print(f"{t = }")
    return t


t1 = [main(10**i, 10) for i in range(1, 8)]
t2 = [main(10, 10**i) for i in range(1, 8)]

plt.plot(t1, label="n1 time process evolution")
plt.plot(t2, label="n2 time process evolution")

plt.xlabel("n-values (log)")
plt.ylabel("Time processing (s)")
plt.title("Insert columns into a numpy array based on mask")
plt.legend()
plt.show()

这是另一种使用cumsum掩码和输入中额外的 0 列进行切片的方法。 cumsum 掩码将具有ip_array + 1 和 0 的索引,只要添加零。 连接数组有一个额外的初始零列,因此使用 0 进行索引会产生一列零。

m = (mask.cumsum()*mask)[0]
# array([0, 1, 2, 0, 3])

np.c_[np.zeros(ip_array.shape[0]), ip_array][:,m].astype(int)

# array([[0, 4, 5, 0, 2],
#        [0, 3, 2, 0, 1],
#        [0, 1, 8, 0, 6]])
mask = np.array([0, 1, 1, 0, 1])
#extract indices of zeros
mask_pos = (list(np.where(mask == 0)[0]))
ip_array =np.array([[4, 5, 2],
        [3, 2, 1],
        [1, 8, 6]])

#insert 0 at respextive mask position
for i in mask_pos:
    ip_array = np.insert(ip_array,i,0,axis=1)

print(ip_array)

暂无
暂无

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

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