我以自己为例:
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/