简体   繁体   中英

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.

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 .

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

沿最后一个轴取其他所有元素,并将它们乘以-1。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM