gpt4 book ai didi

python - 将列表的一维对象 numpy 数组转换为二维数值数组并返回

转载 作者:行者123 更新时间:2023-11-28 22:33:45 25 4
gpt4 key购买 nike

假设我有这个包含相同长度列表的对象数组:

>>> a = np.empty(2, dtype=object)
>>> a[0] = [1, 2, 3, 4]
>>> a[1] = [5, 6, 7, 8]
>>> a
array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=object)
  1. 如何将其转换为数字二维数组?

    >>> a.shape
    (2,)
    >>> b = WHAT_GOES_HERE(a)
    >>> b
    array([[1, 2, 3, 4],
    [5, 6, 7, 8]])
    >>> b.shape
    (2, 4)
  2. 我如何做相反的事情?

  3. 如果我的a 数组是np.arraynp.array,而不是np.array of lists?

    >>> na = np.empty(2, dtype=object)
    >>> na[0] = np.array([1, 2, 3, 4])
    >>> na[1] = np.array([5, 6, 7, 8])
    >>> na
    array([array([1, 2, 3, 4]), ([5, 6, 7, 8])], dtype=object)

最佳答案

一种使用 np.concatenate 的方法-

b = np.concatenate(a).reshape(len(a),*np.shape(a[0]))

@Eric 建议使用 *np.shape(a[0]) 的改进应该使其适用于通用 ND 形状.

sample 运行-

In [183]: a
Out[183]: array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=object)

In [184]: a.shape
Out[184]: (2,)

In [185]: b = np.concatenate(a).reshape(len(a),*np.shape(a[0]))

In [186]: b
Out[186]:
array([[1, 2, 3, 4],
[5, 6, 7, 8]])

In [187]: b.shape
Out[187]: (2, 4)

要返回a,看来我们可以使用两步过程,就像这样-

a_back = np.empty(b.shape[0], dtype=object)
a_back[:] = b.tolist()

sample 运行-

In [190]: a_back = np.empty(b.shape[0], dtype=object)
...: a_back[:] = b.tolist()
...:

In [191]: a_back
Out[191]: array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=object)

In [192]: a_back.shape
Out[192]: (2,)

关于python - 将列表的一维对象 numpy 数组转换为二维数值数组并返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39637486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com