2014-10-08 142 views
1

我想修改一个numpy数组“in-place”。我有兴趣重新安排阵列(而不是返回:重新排列的数组版本)。重新安排numpy阵列

下面是一个例子代码:

from numpy import * 

    def modar(arr): 
    arr=arr[[1,0]] # comment & uncomment this line to get different behaviour 
    arr[:,:]=0 
    print "greetings inside modar:" 
    print arr 

    def test2(): 
    arr=array([[4,5,6],[1,2,3]]) 
    print "array before modding" 
    print arr 
    print 
    modar(arr) 
    print 
    print "array now" 
    print arr 

    test2() 

AR = ARR分配[[1,0]]打破的 “ARR” 原始数组传递给函数 “modar” 的对应关系。您可以通过评论/取消注释该行来确认这一点..当然,这发生了,因为必须创建一个新的数组。

我该如何告诉python新数组仍然对应于“arr”?

简单地说,我怎样才能让“modar”重新排列“in-place”数组?

确定..我修改由该代码和替换 “modarr”:

def modar(arr): 
    # arr=arr[[1,0]] # comment & uncomment this line to get different behaviour 
    # arr[:,:]=0 
    arr2=arr[[1,0]] 
    arr=arr2 
    print "greetings inside modar:" 
    print arr 

例程 “test2的” 仍然得到从 “modar” 未修饰的阵列。

+0

我不明白你的问题。你可以添加一个你期望的函数'modar'的例子吗? – nicoguaro 2014-10-08 12:46:02

+0

“test2”应该从“modar”接收重新排列的数组。 – 2014-10-09 07:41:41

+0

@ElSampsa你尝试了下面的答案吗?你必须这样做:'arr [...] = arr2 [...]''''指示复制数据,否则你会丢失参考 – 2014-10-09 07:48:32

回答

0

在这种情况下,你可以这样做:

arr2 = arr[[1, 0]] 
    arr[...] = arr2[...] 

在临时数组arr2用于存储花哨的索引结果。最后一行将数据从arr2复制到原始数组,保留参考。

注意:一定要在你的操作是arr2拥有的,以避免奇怪的结果arr相同的形状......

+1

好的..我没有仔细阅读你的答案,然后再做自己的..(我会投票给你的)。我试过“arr = arr2”,但是当然,就像你说的那样,它是“arr [:,:] = arr2 [:,:]”。 – 2014-10-09 08:09:21

0

这里是额外玩弄的解决方案。基本上和Saullo一样。

from numpy import * 

def modar1(arr): 
    # arr=arr[[1,0]] # (a) 
    arr[:,:]=arr[[1,0]][:,:] # (b) 
    print "greetings inside modar:" 
    print arr 
    # (a) arr is now referring to a new array .. python does not know if it 
    # has the same type/size as the original parameter array 
    # and therefore "arr" does not point to the original parameter array anymore. DOES NOT WORK. 
    # 
    # (b) explicit copy of each element. WORKS. 

def modar2(arr): 
    arr2=arr.copy() 
    arr2=arr2[[1,0]] 
    # arr=arr2 # (a) 
    arr[:,:]=arr2[:,:] # (b) 
    print "greetings inside modar:" 
    print arr 
    # (a) same problem as in modar1 
    # .. it seems that *any* reference "arr=.." will point "arr" to something else as than original parameter array 
    # and "in-place" modification does not work. DOES NOT WORK 
    # 
    # (b) does an explicit copying of each array element. WORKS 
    # 

def modar3(arr): 
    arr2=arr.copy() 
    arr2=arr2[[1,0]] 
    for i in range(arr.shape[0]): 
    arr[i]=arr2[i] 
    print "greetings inside modar:" 
    print arr 
    # this works, as there is no reference "arr=", i.e. to the whole array 

def test2(): 
    # 
    # the goal: 
    # give an array "arr" to a routine "modar" 
    # After calling that routine, "arr" should appear re-arranged 
    # 
    arr=array([[4,5,6],[1,2,3]]) 
    print "array before modding" 
    print arr 
    print 
    modar1(arr) # OK 
    # modar2(arr) # OK 
    # modar3(arr) # OK 
    print 
    print "array now" 
    print arr 

test2()