Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add a number to all odd or even indexed elements in numpy array without loops

Lets say your numpy array is:

 A =    [1,1,2,3,4]

You can simply do:

A + .1

to add a number to that every element numpy array

I am looking for a way to add a number to just the odd or even indexed numbers A[::2] +1 while keeping the entire array intact.

Is it possible to add a number to all the odd or even indexed elements without any loops?

like image 834
pyCthon Avatar asked Aug 07 '12 15:08

pyCthon


People also ask

How do you print an odd indexed array of elements in Python?

STEP 1: Declare and initialize an array. STEP 2: Calculate the length of the declared array. STEP 3: Loop through the array by initializing the value of variable "i" to 0 then incrementing its value by 2, i.e., i=i+2. STEP 4: Print the elements present in odd positions.


2 Answers

In [43]: A = np.array([1,1,2,3,4], dtype = 'float')

In [44]: A[::2]  += 0.1

In [45]: A
Out[45]: array([ 1.1,  1. ,  2.1,  3. ,  4.1])

Note that this modifies A. If you wish to leave A unmodified, copy A first:

In [46]: A = np.array([1,1,2,3,4], dtype = 'float')

In [47]: B = A.copy()

In [48]: B[::2]  += 0.1

In [49]: B
Out[49]: array([ 1.1,  1. ,  2.1,  3. ,  4.1])

In [50]: A
Out[50]: array([ 1.,  1.,  2.,  3.,  4.])
like image 184
unutbu Avatar answered Sep 20 '22 22:09

unutbu


In addition to previous answers, to modify numbers with odd indices you should use A[1::2] instead of A[::2]

like image 38
Edward Ruchevits Avatar answered Sep 22 '22 22:09

Edward Ruchevits