简体   繁体   English

如何为其他 numpy 数组创建一个 numpy 视图数组

[英]How to create a numpy array of views to other numpy arrays

I have a large list of objects that include numpy arrays as attributes.我有一大堆对象,其中包括 numpy 数组作为属性。 They each have methods that manipulate the array.它们每个都有操作数组的方法。 I would like to create a single 2D numpy array that stores the other arrays and updates when the individual numpy arrays are manipulated.我想创建一个 2D numpy 数组来存储其他数组并在操作单个 numpy 数组时进行更新。

This is easy to accomplish with lists as you simply need to create a list of references to other lists.这很容易通过列表来完成,因为您只需要创建一个对其他列表的引用列表。

>>> x = [1,2,3]
>>> y = [4,5,6]
>>> z = [x,y] # stores reference to x and y
>>> x[0] = 10
>>> z
[[10,2,3],[4,5,6]]

However, doing the same in numpy creates copies of the object.但是,在 numpy 中执行相同操作会创建对象的副本。

>>> x = np.array([1,2,3])
>>> y = np.array([4,5,6])
>>> z = np.array([x,y])  # setting the optional argument copy = False didn't help either
>>> id(x)
140673084678272
>>> id(z[0])
140673084678512

I guessed that setting copy = False wouldn't work because I'm passing a new concatenated list object which hadn't existed before.我猜想设置copy = False是行不通的,因为我正在传递一个以前不存在的新的串联列表对象。 Is there a way to create z where it's elements are references to the numpy arrays x and y ?有没有办法创建z ,它的元素是对 numpy 数组xy的引用?

I recognize that references in numpy are typically accomplished with views , but this seems to be a different use case.我认识到 numpy 中的引用通常是通过views完成的,但这似乎是一个不同的用例。 Creating a view object of a single numpy array is fairly straightforward, but I'm unsure how to store in a numpy array, N view objects from N individual numpy arrays.创建单个 numpy 数组的视图对象相当简单,但我不确定如何将 N 个单独的 numpy 数组中的 N 个视图对象存储在一个 numpy 数组中。

One solution would be to stack() or concatenate() arrays i certain dimensions match.一种解决方案是堆栈()或连接()某些尺寸匹配的数组。 if dims don't match - use padding, store dimensions in separate list and then stack.如果尺寸不匹配 - 使用填充,将尺寸存储在单独的列表中,然后堆叠。

Create an empty object array of the required length (it contains Nulls).创建一个所需长度的空对象数组(它包含 Null)。 Assign the list to a view of the whole array.将列表分配给整个数组的视图。 Done.完毕。 And yes, the original objects update when the individual numpy arrays are manipulated.是的,当操作单个numpy 数组时,原始对象会更新。 Note that operations on the whole array, however, always seem to create copies even when you'd normally expect in-place operations.但是请注意,即使您通常期望就地操作,对整个阵列的操作似乎总是会创建副本。

import numpy as np
x = np.array([1,2,3])
y = np.array([4,5,6])
z = np.empty(2, dtype=object)
z[:] = [x,y]
print(id(x))
print(id(z[0]))

Output:输出:

140293181519152
140293181519152

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM