[英]Convert ndarray of lists to ndarray
nda.shape is (2,2), convert it to be (2,2,2) nda.shape 为 (2,2),将其转换为 (2,2,2)
dtypes = [('a', np.float64), ('b', object)]
nda = np.zeros((2,2), dtype = dtypes)
nda['b'][0,0] = [1,2]
nda['b'][1,0] = [2,3]
nda['b'][0,1] = [3,4]
nda['b'][1,1] = [9,5]
Solution should give: nda['b'][0,0,1]==2
, nda['b'][1,1,0]==9
etc.解决方案应该给出:
nda['b'][0,0,1]==2
, nda['b'][1,1,0]==9
等。
You've created an odd structure;你创建了一个奇怪的结构; you can't simply reshape it:
你不能简单地重塑它:
In [1]: dtypes = [('a', np.float64), ('b', object)]
...: nda = np.zeros((2,2), dtype = dtypes)
...:
...: nda['b'][0,0] = [1,2]
...: nda['b'][1,0] = [2,3]
...: nda['b'][0,1] = [3,4]
...: nda['b'][1,1] = [9,5]
It has 2 fields, one with numbers, the other with lists:它有 2 个字段,一个带有数字,另一个带有列表:
In [2]: nda
Out[2]:
array([[(0., list([1, 2])), (0., list([3, 4]))],
[(0., list([2, 3])), (0., list([9, 5]))]],
dtype=[('a', '<f8'), ('b', 'O')])
The list field:列表字段:
In [3]: nda['b']
Out[3]:
array([[list([1, 2]), list([3, 4])],
[list([2, 3]), list([9, 5])]], dtype=object)
In [4]: _.shape
Out[4]: (2, 2)
If converted to 1d, we can stack
(or otherwise combine with concatenate
):如果转换为 1d,我们可以
stack
(或以其他方式与concatenate
组合):
In [5]: nda['b'].ravel()
Out[5]:
array([list([1, 2]), list([3, 4]), list([2, 3]), list([9, 5])],
dtype=object)
In [6]: np.stack(nda['b'].ravel())
Out[6]:
array([[1, 2],
[3, 4],
[2, 3],
[9, 5]])
In [7]: np.stack(nda['b'].ravel()).reshape(2,2,2)
Out[7]:
array([[[1, 2],
[3, 4]],
[[2, 3],
[9, 5]]])
In general if you have a object dtype array of lists or arrays, it can consolidated into one (numeric) array with sort version of concatenate
, but it has to be 1d, an 'iterable' of arrays/lists.一般来说,如果你有一个 object dtype 列表数组或 arrays,它可以合并到一个(数字)数组中,排序版本为
concatenate
,但它必须是 1d,即数组/列表的“可迭代”。
And, yes, unpacking the field into a nested list produces something that can be converted back to a (2,2,2) array:而且,是的,将字段解压缩到嵌套列表中会产生可以转换回 (2,2,2) 数组的内容:
In [14]: _2['b'].tolist()
Out[14]: [[[1, 2], [3, 4]], [[2, 3], [9, 5]]]
(You can't simply put these arrays (or lists) back into the nda
array. The dtype is wrong.) (您不能简单地将这些 arrays (或列表)放回
nda
数组。dtype 是错误的。)
With a different dtype
(`b field is 2 integers, not the more generic object):使用不同的
dtype
(`b 字段是 2 个整数,而不是更通用的对象):
In [10]: dtypes = [('a', np.float64), ('b', int, (2,))]
...: nda = np.zeros((2,2), dtype = dtypes)
...:
...: nda['b'][0,0] = [1,2]
...: nda['b'][1,0] = [2,3]
...: nda['b'][0,1] = [3,4]
...: nda['b'][1,1] = [9,5]
In [11]: nda
Out[11]:
array([[(0., [1, 2]), (0., [3, 4])],
[(0., [2, 3]), (0., [9, 5])]],
dtype=[('a', '<f8'), ('b', '<i8', (2,))])
In [12]: nda['b']
Out[12]:
array([[[1, 2],
[3, 4]],
[[2, 3],
[9, 5]]])
Try the following尝试以下
nda = np.resize(nda, (2,2,2))
nda.shape
Results结果
(2,2,2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.