NumPy 数组初始化(填充相同的值) [英] NumPy array initialization (fill with identical values)
问题描述
我需要创建一个长度为 n
的 NumPy 数组,其中每个元素都是 v
.
还有什么比:
a = empty(n)对于范围(n)中的我:a[i] = v
我知道 zeros
和 ones
可以用于 v = 0, 1.我可以使用 v *ones(n)
,但它在 会慢得多.v
为 None
时不起作用,而且
NumPy 1.8 引入 np.full()
,这是一种比empty()
后接fill()
更直接的创建数组的方法填充某个值:
这可以说是创建填充某些值的数组的方式,因为它明确描述了要实现的目标(并且原则上可以非常高效,因为它执行非常具体的任务).
I need to create a NumPy array of length n
, each element of which is v
.
Is there anything better than:
a = empty(n)
for i in range(n):
a[i] = v
I know zeros
and ones
would work for v = 0, 1. I could use v * ones(n)
, but it won't work when would be much slower.v
is None
, and also
NumPy 1.8 introduced np.full()
, which is a more direct method than empty()
followed by fill()
for creating an array filled with a certain value:
>>> np.full((3, 5), 7)
array([[ 7., 7., 7., 7., 7.],
[ 7., 7., 7., 7., 7.],
[ 7., 7., 7., 7., 7.]])
>>> np.full((3, 5), 7, dtype=int)
array([[7, 7, 7, 7, 7],
[7, 7, 7, 7, 7],
[7, 7, 7, 7, 7]])
This is arguably the way of creating an array filled with certain values, because it explicitly describes what is being achieved (and it can in principle be very efficient since it performs a very specific task).
这篇关于NumPy 数组初始化(填充相同的值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!