2017-07-06 114 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。