gpt4 book ai didi

python - 使用 zip 和 np.insert 将零部分插入 numpy 数组

转载 作者:太空宇宙 更新时间:2023-11-03 15:47:16 25 4
gpt4 key购买 nike

我剪掉了 numpy 数组的零,做了一些事情,并想将它们插入回视觉目的。我确实有各部分的索引,并尝试使用 numpy.insert 和 zip 将零插入回去,但索引超出范围,即使我从较低端开始。示例:

import numpy as np

a = np.array([1, 2, 4, 0, 0, 0, 3, 6, 2, 0, 0, 1, 3, 0, 0, 0, 5])
a = a[a != 0] # cut zeros out
zero_start = [3, 9, 13]
zero_end = [5, 10, 15]

# Now insert the zeros back in using the former indices
for ev in zip(zero_start, zero_end):
a = np.insert(a, ev[0], np.zeros(ev[1]-ev[0]))

>>> IndexError: index 13 is out of bounds for axis 0 with size 12

似乎他没有刷新循环内的数组大小。有什么建议或其他(更Pythonic)方法来解决这个问题?

最佳答案

方法#1:使用 indexing -

# Get all zero indices
idx = np.concatenate([range(i,j+1) for i,j in zip(zero_start,zero_end)])

# Setup output array of zeros
N = len(idx) + len(a)
out = np.zeros(N,dtype=a.dtype)

# Get mask of non-zero places and assign values from a into those
out[~np.in1d(np.arange(N),idx)] = a

我们还可以生成 a 最初具有非零的实际索引,然后进行分配。因此,掩蔽的最后一步可以用这样的东西代替 -

out[np.setdiff1d(np.arange(N),idx)] = a
<小时/>

方法#2:使用 np.insert给定 zero_startzero_end 作为数组 -

insert_start = np.r_[zero_start[0], zero_start[1:] - zero_end[:-1]-1].cumsum()
out = np.insert(a, np.repeat(insert_start, zero_end - zero_start + 1), 0)

示例运行 -

In [755]: a = np.array([1, 2, 4, 0, 0, 0, 3, 6, 2, 0, 0, 1, 3, 0, 0, 0, 5])
...: a = a[a != 0] # cut zeros out
...: zero_start = np.array([3, 9, 13])
...: zero_end = np.array([5, 10, 15])
...:

In [756]: s0 = np.r_[zero_start[0], zero_start[1:] - zero_end[:-1]-1].cumsum()

In [757]: np.insert(a, np.repeat(s0, zero_end - zero_start + 1), 0)
Out[757]: array([1, 2, 4, 0, 0, 0, 3, 6, 2, 0, 0, 1, 3, 0, 0, 0, 5])

关于python - 使用 zip 和 np.insert 将零部分插入 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41643902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com