繁体   English   中英

预分配numpy数组的numpy数组

[英]preallocation of numpy array of numpy arrays

我读到了预分配numpy数组的重要性。 但就我而言,我不知道该怎么做。 我想预先分配一个nxm矩阵。 这听起来很简单

M = np.zeros((n,m))

但是,如果我的矩阵是矩阵矩阵怎么办? 那么如果这些nxm元素中的每一个实际上都是这种形式呢?

np.array([[t], [x0,x1,x2], [y0,y1,y2]])

我知道在那种情况下,M会有形状(n,m,3)。 举个例子,后来我想要这样的东西

[[[[0], [0,1,2], [3,4,5]],
    [[1], [10,11,12], [13,14,15]]], 
[[[0], [100,101,102], [103,104,105]],
    [[1], [110,111,112], [113,114,115]]]]

我试着干脆做

M = np.zeros((2,2,3))

但是之后

M[0,0,:] = np.array([[0], [0,1,2], [3,4,5]])

会给我一个错误

ValueError:使用序列设置数组元素。

我可以不预先分配这个怪物吗? 或者我应该以完全不同的方式处理这个问题?

谢谢你的帮助

如果你知道你只存储n,m每个点的值t, y, x n,m那么拥有三个numpy数组可能更容易,计算速度更快。

所以:

M_T = np.zeros((n,m))
M_Y = np.zeros((n,m))
M_X = np.zeros((n,m))

我相信你现在可以输入'普通'python运算符来做数组逻辑,例如:

MX = np.ones((n,m))
MY = np.ones((n,m))
MT = MX + MY
MT ** MT
_ * 7.5

通过定义数组友好函数(类似于MATLAB),您可以大大提高计算速度。

当然,如果您在每个点需要更多变量,那么这可能变得难以处理。

您必须确保在每个维度上预先分配正确数量的维度和元素,以使用简单的分配来填充它。

例如,您想要保存3个2x3矩阵:

number_of_matrices = 3
matrix_dim_1 = 2
matrix_dim_2 = 3

M = np.empty((number_of_matrices, matrix_dim_1, matrix_dim_2))
M[0] = np.array([[  0,   1,   2], [  3,   4,   5]])
M[1] = np.array([[100, 101, 102], [103, 104, 105]])
M[2] = np.array([[ 10,  11,  12], [ 13,  14,  15]])

M
#array([[[   0.,    1.,    2.],           # matrix 1
#        [   3.,    4.,    5.]],
# 
#        [[ 100.,  101.,  102.],          # matrix 2
#        [ 103.,  104.,  105.]],
#
#       [[  10.,   11.,   12.],           # matrix 3
#        [  13.,   14.,   15.]]])

你的方法包含一些问题。 要保存的数组不是有效的ndimensional numpy数组:

np.array([[0], [0,1,2], [3,4,5]])
# array([[0], [0, 1, 2], [3, 4, 5]], dtype=object)
#                                    |----!!----|
#         ^-------^----------^       3 items in first dimension
#         ^                          1 item in first item of 2nd dim
#              ^--^--^               3 items in second item of 2nd dim
#                         ^--^--^    3 items in third item of 2nd dim    

它只是创建一个包含python list对象的3项数组。 您可能希望有一个包含数字的数组,因此您需要关注维度。 你的np.array([[0], [0,1,2], [3,4,5]])可能是一个3x1数组或一个3x3数组,numpy不知道在这种情况下该做什么并保存它作为对象(数组现在只有1维!)。


另一个问题是您希望将预分配数组的一个元素设置为包含多个元素的另一个数组。 这是不可能的(除了你已经有一个object -array)。 你有两个选择:

  1. 在数组所需的预分配数组中填充尽可能多的元素:

     M[0, :, :] = np.array([[0,1,2], [3,4,5]]) # ^--------------------^--------^ First dimension has 2 items # ^---------------^-^-^ Second dimension has 3 items # ^------------------------^-^-^ dito # if it's the first dimension you could also use M[0] 
  2. 创建一个object数组并设置元素( 不推荐,你放弃了numpy数组的大部分优点 ):

     M = np.empty((3), dtype='object') M[0] = np.array([[0,1,2], [3,4,5]]) M[1] = np.array([[0,1,2], [3,4,5]]) M[2] = np.array([[0,1,2], [3,4,5]]) M #array([array([[0, 1, 2], # [3, 4, 5]]), # array([[0, 1, 2], # [3, 4, 5]]), # array([[0, 1, 2], # [3, 4, 5]])], dtype=object) 

暂无
暂无

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

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