重新安排numpy数组到位 [英] Re-arranging numpy array in place

查看:125
本文介绍了重新安排numpy数组到位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试就地"修改一个numpy数组.我对就地重新排列数组感兴趣(而不是返回:重新排列数组版本).

I am trying to modify a numpy array "in-place". I am interested in re-arranging the array in-place (instead of return:ing a re-arranged version of the array).

这是示例代码:

  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"的原始数组的对应关系.您可以通过注释/取消注释该行来确认这一点.当然,这是因为必须创建一个新数组.

The assignment ar=arr[[1,0]] breaks the correspondence of "arr" to the original array passed to the function "modar". You can confirm this by commenting/uncommenting that line.. this happens, of course, as a new array has to be created.

如何告诉python新数组仍然对应于"arr"?

How can I tell python that the new array still corresponds to "arr"?

简而言之,我该如何使模态"重新排列数组就地"?

Simply, how can I make "modar" to rearrange the array "in-place"?

好吧.我修改了该代码,并将"modarr"替换为:

Ok.. I modified that code and replaced "modarr" by:

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"获取未经修改的数组.

The routine "test2" still gets an unmodified array from "modar".

推荐答案

在这种情况下,您可以执行以下操作:

In this case you could do:

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

其中临时数组arr2用于存储花式索引结果.最后一行将数据从arr2复制到原始数组,并保留引用.

where the temporary array arr2 is used to store the fancy indexing result. The last line copies the data from arr2 to the original array, keeping the reference.

注意:请确保您的操作中arr2具有与arr相同的形状,以避免出现奇怪的结果...

Note: be sure in your operations that arr2 has the same shape of arr in order to avoid strange results...

这篇关于重新安排numpy数组到位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆