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?
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.
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.])
                        In addition to previous answers, to modify numbers with odd indices you should use A[1::2] instead of A[::2]
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