Scalar Multipliction Numpy

Viewed 42

I need to multiply a scalar value to a numpy array starting from a specific element.

eg) 3 * [1,1,1,1,1,1] = [1,3,3,3,3,3]

I have tried to do np.dot(value, arr[1:]), but this removes the first element. How would I do this?

2 Answers

Is your data a numpy array or a python array? For numpy array:

a[1:] *= 3

For python array:

for i in range(1,len(a)): a[i] *= 3

Note: Of course the python approach works for numpy arrays as well, but it wouldn't take advantage of numpy's vectorization.

arr = np.array([1,1,1,1])
arr[1:] *= 2

or

arr = np.array([1,1,1,1])
arr[1:] = 2*arr[1:]

gives

arr->array([1, 2, 2, 2])
Related