使用固定值预填充numpy数组

zqry0prt  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(89)

如何在使用固定值初始化numpy数组时进行预填充?我尝试生成list并将其用作fill

>>> c = np.empty(5)
>>> c
array([0.0e+000, 9.9e-324, 1.5e-323, 2.0e-323, 2.5e-323])
>>> np.array(list(range(0,10,1)))
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> 
 
>>> c.fill(np.array(list(range(0,10,1))))
TypeError: only length-1 arrays can be converted to Python scalars

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: setting an array element with a sequence.

>>> c.fill([np.array(list(range(0,10,1)))])
TypeError: float() argument must be a string or a real number, not 'list'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: setting an array element with a sequence.

字符串
预期-

array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])

xriantvc

xriantvc1#

fill用相同的值填充每个条目。c = np.empty(size); c.fill(5)分配一个大小为size的数组,而不初始化任何值,然后用所有的5填充它。
除了AJ Biffl的答案,你也可以通过广播给ndarray赋值:

c = np.empty(5)
c[:] = range(5)

字符串
这只适用于形状匹配的情况,但它确实可以让你做这样的事情:

a = np.empty((5, 3))
a[:] = [range(i, i+3) for i in range(5)]

>>> array([[0., 1., 2.],
       [1., 2., 3.],
       [2., 3., 4.],
       [3., 4., 5.],
       [4., 5., 6.]])

wz3gfoph

wz3gfoph2#

第一个月
np.arange(10)创建从0到9的整数数组
np.tile(..., (5,1))平铺阵列的副本- 5个副本“向下”(新行)和1个“交叉”(每行内1个副本)

相关问题