我希望编写一个setitem函数,用另一个数组替换numpy数组的子集,该数组的长度可能相同,也可能不同。shape[0](但列大小始终相同。shape[1])
例如,使用numpy.put()
将绑定到数组的形状
a = np.arange(10)
np.put(a, [2,3], [80, 80, 80, 80])
array([ 0, 1, 80, 80, 4, 5, 6, 7, 8, 9])
但我希望将a
扩展到一个新的形状:
array([ 0, 1, 80, 80, 80, 80, 4, 5, 6, 7, 8, 9])
目前我所做的是根据新形状创建一个新数组。然后相应地分配每个零件:
a = np.ones((10, 2)) * 2
b = np.ones((4, 2)) * 80
def insert(a, pos, b):
start = pos[0]; end = start + b.shape[0]
c = np.ndarray((b.shape[0] - len(pos) + a.shape[0], a.shape[1]))
c[:start] = a[:start] # The first part is still a
c[start:end] = b # The middle part being replace by b
c[end:] = a[pos[-1] + 1:] # The remaining is also a .
return c
a = insert(a, [2, 3], b) # Insert a longer to array to the position
array([[ 2., 2.],
[ 2., 2.],
[80., 80.],
[80., 80.],
[80., 80.],
[80., 80.],
[ 2., 2.],
[ 2., 2.],
[ 2., 2.],
[ 2., 2.],
[ 2., 2.],
[ 2., 2.]])
d = insert(a, [2,3,4,5,6], b) # Insert a shorter array to the position
array([[ 2., 2.],
[ 2., 2.],
[80., 80.],
[80., 80.],
[80., 80.],
[80., 80.],
[ 2., 2.],
[ 2., 2.],
[ 2., 2.]])
它似乎工作,但也似乎非常低效,因为我处理的音频数据,所以大小相当大
请建议是否有一个更python或numpy的方法来有效地插入一个不匹配大小的数组到另一个数组
目前没有回答
相关问题 更多 >
编程相关推荐