简体   繁体   English

创建列表的多维numpy数组,并为第一个元素依次分配一个数字

[英]Create multidimensional numpy array of lists and assign first element a number in sequence

I'm looking to create a numpy array of lists and define the first element in each list as a number in sequence. 我正在寻找创建一个列表的numpy数组,并将每个列表中的第一个元素定义为数字顺序。

So far I can create the numpy array of all the first elements but they are not nested within lists as I'd like. 到目前为止,我可以创建所有第一个元素的numpy数组,但是它们并没有按照我的意愿嵌套在列表中。

So I have 所以我有

 B=np.arange(1,10)
 Bnew = B.reshape((3,3))
 array([[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]])

but I want it to look like: 但我希望它看起来像:

 array([[[1], [2], [3]],
        [[4], [5], [6]],
        [[7], [8], [9]]])

as I will be adding more numbers to each list component as I continue to modify the matrix. 因为随着我继续修改矩阵,我将向每个列表组件添加更多数字。

Thanks! 谢谢!

To be able to append to the cells of your array you need to make it dtype=object . 为了能够附加到数组的单元格,需要将其设置为dtype=object You can force that using the following slightly ugly hack 您可以使用以下略微难看的技巧来强制使用

a = [[i] for i in range(1, 10)]
swap = a[0]
a[0] = None # <-- this prevents the array factory from converting
            #     the innermost level of lists into an array dimension
b = np.array(a)
b[0] = swap
b.shape = 3, 3

now you can for example do 现在您可以例如

b[1,1].append(2)
b
array([[[1], [2], [3]],
       [[4], [5, 2], [6]],
       [[7], [8], [9]]], dtype=object)

What you want is a 3-dimensional numpy array. 您想要的是3维numpy数组。 But reshape((3, 3)) will create a 2-dimensional array, because you are providing two dimensions to it. 但是reshape((3, 3))将创建一个二维数组,因为您要为其提供二维。 To create what you want, you should give a 3D shape to the reshape function: 要创建所需的内容,应为reshape函数赋予3D形状:

Bnew = B.reshape((3, 3, 1)) 

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

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