无法使用 numpy 的 'full()' 方法和 python 列表创建 numpy 数组



我可以从python列表中创建一个numpy数组,如下所示:

>>> a = [1,2,3]
>>> b = np.array(a).reshape(3,1)
>>> print(b)
[[1]
[2]
[3]]

然而,我不知道是什么原因导致以下代码出错:

代码:

>>> a = [1,2,3]
>>> b = np.full((3,1), a)

错误:

ValueError                                Traceback (most recent call last)
<ipython-input-275-1ab6c109dda4> in <module>()
1 a = [1,2,3]
----> 2 b = np.full((3,1), a)
3 print(b)
/usr/local/lib/python3.6/dist-packages/numpy/core/numeric.py in full(shape, fill_value, dtype, order)
324         dtype = array(fill_value).dtype
325     a = empty(shape, dtype, order)
--> 326     multiarray.copyto(a, fill_value, casting='unsafe')
327     return a
328 
<__array_function__ internals> in copyto(*args, **kwargs)
ValueError: could not broadcast input array from shape (3) into shape (3,1)

尽管列表a中有3个元素,并且我希望有一个3x1 numpy数组,但full()方法无法提供它。我也参考了numpy的广播文章。然而,他们更关注算术运算的角度,因此我无法从中获得任何有用的东西。

所以,如果你能帮我理解b/w的区别,那就太好了。上面提到的数组创建方法以及错误的原因。

Numpy无法同时广播这两个形状,因为当您请求"列向量"(shape=(3, 1)(时,您的列表被解释为"行向量"(np.array(a).shape = (3,)(。如果您已设置使用np.full,那么您可以将列表最初形成为列向量:

>>> import numpy as np
>>>
>>> a = [[1],[2],[3]]
>>> b = np.full((3,1), a)

另一种选择是提前将a转换为numpy数组,并添加一个新轴以匹配所需的输出形状。

>>> a = [1,2,3]
>>> a = np.array(a)[:, np.newaxis]
>>> b = np.full((3,1), a)

最新更新