Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 654
Ébe Isaac Avatar asked Sep 12 '15 19:09

Ébe Isaac


People also ask

How do I add values to an array in NumPy?

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.

How do you add numbers to an array in Python?

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.

What is scalar type in NumPy?

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_, ...


1 Answers

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])
like image 98
Alexander Avatar answered Oct 25 '22 20:10

Alexander