【问题标题】:convert a list of numpy arrays into a numpy array in which elements are numpy arrays将 numpy 数组列表转换为 numpy 数组,其中元素是 numpy 数组
【发布时间】:2022-02-10 01:33:43
【问题描述】:

将 numpy 数组列表转换为以 numpy 数组为元素的 numpy 数组的 Python 代码?

我有一个数组列表如下:

my_list

输出:

[array([1,2,3]),
    array(['a', 'b','c]),
    array(['text1', 'text2', 'text3'])
    ]

使用 np.asarray() 将元素转换为如下所示的列表:

my_array = np.asarray(my_list)

my_array 看起来像:

array([[1,2,3],['a', 'b','c], ['text1', 'text2', 'text3']])

我想要的输出类型:

array([array([1,2,3]),array(['a', 'b','c]),array(['text1', 'text2', 'text3'])])

有人可以帮我写代码吗?

【问题讨论】:

  • 您为什么要这样做?它没有什么好用的。实际上任何行/列已经是一个 numpy 数组。在您的情况下,只需使用列表
  • 您的阵列需要在形状上有所不同。但是清单有什么问题?您希望通过制作阵列获得什么?

标签: python list numpy


【解决方案1】:
In [173]: alist = [np.array([1,2,3]),
     ...:     np.array(['a', 'b','c']),
     ...:     np.array(['text1', 'text2', 'text3'])
     ...:     ]
In [174]: alist
Out[174]: 
[array([1, 2, 3]),
 array(['a', 'b', 'c'], dtype='<U1'),
 array(['text1', 'text2', 'text3'], dtype='<U5')]
In [175]: np.array(alist)
Out[175]: 
array([['1', '2', '3'],
       ['a', 'b', 'c'],
       ['text1', 'text2', 'text3']], dtype='<U21')

np.array 尝试使多维数组尽可能高。 3个大小相同的数组可以组成一个(3,3)。

为避免我们必须创建所需形状和 dtype 的目标数组,并从列表中分配值:

In [178]: arr = np.empty(3, object)
In [179]: arr[:] = alist
In [180]: arr
Out[180]: 
array([array([1, 2, 3]), array(['a', 'b', 'c'], dtype='<U1'),
       array(['text1', 'text2', 'text3'], dtype='<U5')], dtype=object)

如果列表包含不同大小的数组(或其他对象),np.array 回退到为这些项目创建一个对象 dtype 数组。但请注意警告,并记住这是一个后备选项,并且如您所见,不是默认行为。

In [181]: alist.append([1,2])
In [182]: np.array(alist)
<ipython-input-182-7512d762195a>: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.
  np.array(alist)
Out[182]: 
array([array([1, 2, 3]), array(['a', 'b', 'c'], dtype='<U1'),
       array(['text1', 'text2', 'text3'], dtype='<U5'), list([1, 2])],
      dtype=object)

再说一遍我的评论 - 为什么你想要一个数组数组?与原始列表相比,这有什么优势?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-08
    • 2019-08-30
    • 1970-01-01
    • 2021-06-09
    • 2021-12-18
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    相关资源
    最近更新 更多