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.
Use append() to add an element to Numpy Array. Use concatenate() to add an element to Numpy Array. Use insert() to add an element to Numpy Array.
Adding to an array using array moduleBy using append() function : It adds elements to the end of the array. By using insert() function : It inserts the elements at the given index. By using extend() function : It elongates the list by appending elements from both the lists.
A NumPy scalar is any object which is an instance of np.generic or whose type is in np.ScalarType : In [12]: np.ScalarType Out[13]: (int, float, complex, long, bool, str, unicode, buffer, numpy.int16, numpy.float16, numpy.int8, numpy.uint64, numpy.complex192, numpy.void, numpy.uint32, numpy.complex128, numpy.unicode_, ...
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With