python - numpy.array() 等同于 numpy.stack(..., axis=0) 吗?

标签 python arrays numpy

我以自己为例:

import numpy as np
arrays = [np.random.rand(3,4) for _ in range(10)]
arr1 = np.array(arrays)
print(arr1.shape)
arr2 = np.stack(arrays, axis=0)
print(arr2.shape)

我发现arr1和arr2具有相同的形状和内容。那么这两个方法(np.array() 和 np.stack(..., axis=0) 等价吗?

最佳答案

一般来说,您应该从两者中得到类似的结果,但会有一些边缘情况。例如,将不规则列表传递给 np.array 将给出一个 np.array 列表,但 np.stack 将引发异常:

In [119]: np.stack([[1,2], [4,5,6]], axis=0)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-119-2ba66e6300d6> in <module>()
----> 1 np.stack([[1,2], [4,5,6]], axis=0)

<__array_function__ internals> in stack(*args, **kwargs)

    423     shapes = {arr.shape for arr in arrays}
    424     if len(shapes) != 1:
--> 425         raise ValueError('all input arrays must have the same shape')
    426
    427     result_ndim = arrays[0].ndim + 1

ValueError: all input arrays must have the same shape

In [120]: np.array([[1,2], [4,5,6]])
Out[120]: array([list([1, 2]), list([4, 5, 6])], dtype=object)

关于python - numpy.array() 等同于 numpy.stack(..., axis=0) 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58387271/

相关文章:

python - 使用抓取算法分离显着区域

c - 为什么可变长度数组在此 C 代码中工作?

python - xtensor 类型的性能与 NumPy 的简单归约

python - 将 2-D numpy 数组附加到 3-D numpy 数组

python - 如何在检测空列表的嵌套列表时返回 True?

python - Django - 捕获异常

python - 类型错误 : ObjectId ('' ) is not JSON serializable

c++ - 将 '_' 更改为 ' ' 根本不起作用

c# - 如何向数组添加关联索引。 C#

python - 表示连接切片的切片