Joseph
Joseph

Reputation: 329

Changing elements in a numpy Array

I have been sifting through the Numpy tutorials and I've tried several functions that are not working for me. I want to take an array such as:

    import numpy as np
    a = np.array([[[1, 2, 3, 4]],[[5, 6, 7, 8]],[[1, 2, 3, 4]],[[5, 6, 7, 8]]])

which has the form

     [[[1 2 3 4]]

     [[4 5 6 7]]

     [[1 2 3 4]]

     [[4 5 6 7]]]

This is the format a different function gives me results in, so, the form is not by choosing. What I want to do is make every other element negative, so it would look like

     [[[1 -2 3 -4]]

     [[4 -5 6 -7]]

     [[1 -2 3 -4]]

     [[4 -5 6 -7]]]

I tried np.negative(a) and that made every element negative. There is a where option that I thought I could make use of, but, I couldn't find a way to have it affect only every other component. I've also built a double loop to move through the array as lists, but, I can't seem to rebuild the array from these lists

     new = np.array([])

     for n in range(len(a)):
         for x1,y1,x2,y2 in a[n]:
              y1 = -1 * y1
              y2 = -1 * y2
             row = [x1, y1, x2, y2]
         new = np.append(new,row)
     print(a)

I feel like I'm making this too complicated, but, a better approach hasn't occurred to me.

Upvotes: 1

Views: 1791

Answers (2)

akuiper
akuiper

Reputation: 214927

You can multiple every other column by -1 combined with slice:

a[...,1::2] *= -1
# here use ... to skip the first few dimensions, and slice the last dimension with 1::2 
# which takes element from 1 with a step of 2 (every other element in the last dimension)
# now multiply with -1 and assign it back to the exact same locations

a
#array([[[ 1, -2,  3, -4]],

#       [[ 5, -6,  7, -8]],

#       [[ 1, -2,  3, -4]],

#       [[ 5, -6,  7, -8]]])

You can see more about ellipsis here.

Upvotes: 2

user2357112
user2357112

Reputation: 280251

a[..., 1::2] *= -1

Take every other element along the last axis and multiply them by -1.

Upvotes: 2

Related Questions