在p中重新排列numpy数组

2024-03-28 14:06:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试“就地”修改numpy数组。我有兴趣在适当的位置重新安排阵列(而不是返回:ing a阵列的重新排列版本)。你知道吗

下面是一个示例代码:

  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”重新排列数组“就位”?你知道吗

好的。。我修改了代码并将“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”获取未修改的数组。你知道吗


Tags: to代码numpygetdeflinecomment数组
3条回答

这里有一个额外的解决方案。基本上和索洛的一样

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

"For all cases of index arrays, what is returned is a copy of the original data, not a view as one gets for slices."

http://docs.scipy.org/doc/numpy/user/basics.indexing.html

在这种情况下,您可以:

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

其中临时数组arr2用于存储奇特的索引结果。最后一行将数据从arr2复制到原始数组,保留引用。你知道吗

注意:确保在操作中arr2具有相同的arr形状,以避免出现奇怪的结果。。。你知道吗

相关问题 更多 >