简体   繁体   English

将多维列表转换为多维numpy.array

[英]Convert multidimensional list to multidimensional numpy.array

I am having trouble converting a python list-of-list-of-list to a 3 dimensional numpy array. 我在将python-list-of-list-of-list转换为3维numpy数组时遇到麻烦。

a = [
   [ 
     [1,2,3,4], # = len 4
     ...
   ], # = len 58
   ...
] # = len 1245

when I call a = np.array(a) on it, it reports shape as (1245,) and I cannot reshape it. 当我在上面调用a = np.array(a)时,它报告形状为(1245,)而我无法对其进行整形。 a.reshape(1245,58,4) It gives me the error: ValueError: cannot reshape array of size 1245 into shape (1245,58,4) But If I print a[0] it gives me a 58 element list and a[0][0] gives me a 4 element list, as I expected, so the data is there. a.reshape(1245,58,4)它给我错误: ValueError: cannot reshape array of size 1245 into shape (1245,58,4)但是如果我打印a [0],它会给我58元素列表和一个正如我所期望的,[0] [0]给了我4个元素的列表,因此数据就在那里。

I see plenty of stack exchange posts wanting to flatten it, but I just want to make it into a numpy array in the shape that it already is. 我看到很多堆栈交换帖子都希望将其扁平化,但我只想将其变成已经是形状的numpy数组。 I don't know why numpy.array() is not seeing the other dimensions. 我不知道为什么numpy.array()没有看到其他尺寸。

Lists of the same level (the same numpy axis) need to be the same size. 相同级别(相同numpy轴)的列表的大小必须相同。 Otherwise you get an array of lists. 否则,您将获得一个列表数组。

np.array([[0, 1], [2]])[0]  # returns [0, 1]

np.array([[0, 1], [2, 3]])[0]  # returns array([1, 2])

You can get around this by calling [ pad ] on your lists before converting them to an array. 您可以通过将列表转换为数组之前调用列表中的[ pad ]来解决此问题。

Furthermore the dimensions for reshape "should be compatible with the original shape." 此外, reshape的尺寸“应与原始形状兼容”。 Meaning (with the exception of a -1 value for inference) the product of the new dimensions should equal the product of the old dimensions. 含义(推理时为-1值除外)新尺寸的乘积应等于旧尺寸的乘积。

For example in your case you have an array of shape (1245,) so you could call: 例如,在您的情况下,您有一个形状数组(1245,)因此可以调用:

a.reshape(83, 5, 3)  # works
a.reshape(83, -1, 3)  # works
a.reshape(83, 5, 5)  # fails since 83 * 5 * 5 = 2075 != 1245

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

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