我想将一系列不同大小的数组存储到一个“父”数组中。像这样:
import numpy as np a1 = np.array([[1,2], [3,4], [5,6]]) a2 = np.array([7,3]) a3 = np.array([1]) # What I want to do a_parent = np.ndarray(a1, a2, a3) # Desired output print(a_parent[0]) >>> [[1 2] [3 4] [5 6]] print(a_parent[1]) >>> [7 3] print(a_parent[2]) >>> [1]
loadmat我知道这是可能的,因为当我从库中导入 Matlab 单元格数据时,scipy.io数据会转换为 numpy ndarray,其行为与上述完全相同。我查看了numpy 文档,但找不到一个可行的示例来展示如何自己做到这一点。
loadmat
scipy.io
ndarray
In [5]: a1 = np.array([[1,2], [3,4], [5,6]]) ...: a2 = np.array([7,3]) ...: a3 = np.array([1])
最好的方法是创建所需数据类型和形状的“空白”数组:
In [6]: a_parent = np.empty(3, object) In [7]: a_parent Out[7]: array([None, None, None], dtype=object)
并从所需数组(或其他对象)的列表中“填充”它:
In [13]: a_parent[:] = [a1,a2,a3] In [14]: a_parent Out[14]: array([array([[1, 2], [3, 4], [5, 6]]), array([7, 3]), array([1])], dtype=object)
我确信loadmat使用这个方法。
直接传递列表np.array可能会有效,但 v1.19 要求我们包含objectdtype:
np.array
object
In [10]: np.array([a1,a2,a3]) /usr/local/bin/ipython3:1: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray #!/usr/bin/python3 Out[10]: array([array([[1, 2], [3, 4], [5, 6]]), array([7, 3]), array([1])], dtype=object)
如果数组都是相同形状,则此方法不起作用:
In [11]: np.array([a1,a1]) Out[11]: array([[[1, 2], [3, 4], [5, 6]], [[1, 2], [3, 4], [5, 6]]])
对于某些形状组合,我们会出现错误。
In [15]: a_parent[:] = [a3,a3,a3] In [16]: a_parent Out[16]: array([array([1]), array([1]), array([1])], dtype=object)