How to add a scalar to a numpy array within a specific range?

♀尐吖头ヾ 提交于 2021-02-08 12:23:46

问题


Is there a simpler and more memory efficient way to do the following in numpy alone.

import numpy as np
ar = np.array(a[l:r])
ar += c
a = a[0:l] + ar.tolist() + a[r:]

It may look primitive but it involves obtaining a subarray copy of the given array, then prepare two more copies of the same to append in left and right direction in addition to the scalar add. I was hoping to find some more optimized way of doing this. I would like a solution that is completely in Python list or NumPy array, but not both as converting from one form to another as shown above would cause serious overhead when the data is huge.


回答1:


You can just do the assignment inplace as follows:

import numpy as np

a = np.array([1, 1, 1, 1, 1])
a[2:4] += 5
>>> a
array([1, 1, 6, 6, 1])


来源:https://stackoverflow.com/questions/32542689/how-to-add-a-scalar-to-a-numpy-array-within-a-specific-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!