14

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?

2
  • why does it need to be without loops? could you show your code? where you want to implement this in the code?
    – Inbar Rose
    Aug 7, 2012 at 16:01
  • 1
    What does "while keeping the entire array intact" mean? Are you ruling out in-place operations?
    – DSM
    Aug 7, 2012 at 16:02

4 Answers 4

25
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.])
1
  • What if we have a 2D array, if j+j is even we add zero?
    – Paulo
    Aug 20, 2021 at 9:49
16

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

2

Something with list comprehension could work.

A = [1,1,2,3,4]
A = [A[i] + (0 if (i%2 == 0) else .1) for i in range(len(A))]

Just quick and dirty with a ternary. Might not work in your version of Python, can't remember which versions it works with.


Checked in Python 2.7.3 and Python 3.2.3, output is the same:

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

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

>>> A = [A[i] + (0 if (i%2 == 0) else .1) for i in range(len(A))]

>>> A
[1, 1.1, 2, 3.1, 4]
1
  • Ah, missed the numpy array bit. The first answer is much better. My bad.
    – DrGodCarl
    Aug 7, 2012 at 16:15
0

If the list didn't start with two 1 and you wanted to add to all even numbers, you could use:

A[1::2] += 0.1

or

A[::-2][::-1] += 0.1

In the latter case, [::-1] is used to reverse the array back to normal order.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.