重新安排numpy数组到位

编程入门 行业动态 更新时间:2024-10-18 19:24:08
本文介绍了重新安排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数组到位

本文发布于:2023-07-14 09:59:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1104035.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   numpy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!