2017-07-06 113 views
1

我一直在浏览Numpy教程,并尝试了几个不适合我的函数。我想利用数组如:在numpy数组中更改元素

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

它的形式

 [[[1 2 3 4]] 

    [[4 5 6 7]] 

    [[1 2 3 4]] 

    [[4 5 6 7]]] 

这是格式不同的功能给我造成,所以,形式是不是选择。我想要做的就是让所有其他元素负,所以它看起来像

 [[[1 -2 3 -4]] 

    [[4 -5 6 -7]] 

    [[1 -2 3 -4]] 

    [[4 -5 6 -7]]] 

我想np.negative(a),这让每一个元素负。有一个where选项,我认为我可以利用,但是,我找不到一种方法来影响只有每一个其他组件。我还内置了双循环遍历数组列表移动,但是,我似乎无法从这些清单

 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) 

我觉得我做这个太复杂了重建阵列,但是,我没有想到更好的方法。

回答

2

您可以将多个由-1结合每隔一列:

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]]]) 

你可以看到更多的省略号here

+0

似乎完美的工作,我显然需要了解数组的数学,我不太明白,代码 – Joseph

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

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