numpy的数组初始化(具有相同值填写)

numpy的数组初始化(具有相同值填写)

问题描述:

我需要创建长度的numpy的阵列 N ,每个元素都是其中 v

I need to create a numpy array of length n, each element of which is v.

有什么比更好的:

a = empty(n)
for i in range(n):
    a[i] = v

我知道那些将为V = 0的工作,1。我可以用 v *的人(N),但它不会工作,当 v ,也将慢得多。

I know zeros and ones would work for v = 0, 1. I could use v * ones(n), but it won't work when v is None, and also would be much slower.

numpy的1.8引入了np.full()$c$c>,这是比一个更直接的方法空()然后按填写()创建充满一定值的数组

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).