简体   繁体   English

一个简单的问题:在numpy中,您如何制作多维数组数组?

[英]Simple question: In numpy how do you make a multidimensional array of arrays?

Right, perhaps I should be using the normal Python lists for this, but here goes: 是的,也许我应该为此使用普通的Python列表,但是这里有:

I want a 9 by 4 multidimensional array/matrix (whatever really) that I want to store arrays in. These arrays will be 1-dimensional and of length 4096. 我想要一个9 x 4的多维数组/矩阵(无论如何),我想将数组存储在其中。这些数组将是一维的,长度为4096。

So, I want to be able to go something like 所以,我希望能够走类似

column = 0                                    #column to insert into
row = 7                                       #row to insert into
storageMatrix[column,row][0] = NEW_VALUE
storageMatrix[column,row][4092] = NEW_VALUE_2
etc..

I appreciate I could be doing something a bit silly/unnecessary here, but it will make it ALOT easier for me to have it structured like this in my code (as there's alot of these, and alot of analysis to be done later). 我很高兴在这里可以做一些愚蠢/不必要的事情,但这将使我在代码中像这样进行结构化变得很容易(因为其中有很多,以后还要进行很多分析)。

Thanks! 谢谢!

Note that to leverage the full power of numpy, you'd be much better off with a 3-dimensional numpy array. 请注意,要利用numpy的全部功能,使用3维numpy数组会更好。 Breaking apart the 3-d array into a 2-d array with 1-d values may complicate your code and force you to use loops instead of built-in numpy functions. 将3-d数组拆分为具有1-d值的2-d数组可能会使您的代码复杂化,并迫使您使用循环而不是内置的numpy函数。

It may be worth investing the time to refactor your code to use the superior 3-d numpy arrays. 可能值得花时间重构代码以使用高级3-d numpy数组。

However, if that's not an option, then: 但是,如果这不是一个选择,则:

import numpy as np
storageMatrix=np.empty((4,9),dtype='object')

By setting the dtype to 'object' , we are telling numpy to allow each element of storageMatrix to be an arbitrary Python object. 通过将dtype设置为'object' ,我们告诉numpy允许storageMatrix每个元素都是任意的Python对象。

Now you must initialize each element of the numpy array to be an 1-d numpy array: 现在,您必须将numpy数组的每个元素初始化为1-d numpy数组:

storageMatrix[column,row]=np.arange(4096)

And then you can access the array elements like this: 然后您可以像这样访问数组元素:

storageMatrix[column,row][0] = 1
storageMatrix[column,row][4092] = 2

The Tentative NumPy Tutorial says you can declare a 2D array using the comma operator: 暂定的NumPy教程说,您可以使用逗号运算符声明2D数组:

x = ones( (3,4) )

and index into a 2D array like this: 并像这样索引到二维数组中:

>>> x[1,2] = 20
>>> x[1,:]                             # x's second row
array([ 1,  1, 20,  1])
>>> x[0] = a                           # change first row of x
>>> x
array([[10, 20, -7, -3],
       [ 1,  1, 20,  1],
       [ 1,  1,  1,  1]])

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

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