如何创建N个相同值的Numpy数组?

Sha*_*ang 1 python arrays numpy

这肯定是一个简单的问题:

如何创建N值的numpy数组,所有相同的值?

例如,numpy.arange(10)创建10个从0到9的整数值.

array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Run Code Online (Sandbox Code Playgroud)

我想创建一个由10个相同整数值组成的numpy数组,

array([3, 3, 3, 3, 3, 3, 3, 3, 3, 3])
Run Code Online (Sandbox Code Playgroud)

Dan*_*enz 9

用途numpy.full():

>> import numpy as np

>> np.full(
    shape=10,
    fill_value=3,
    dtype=np.int)

array([3, 3, 3, 3, 3, 3, 3, 3, 3, 3])
Run Code Online (Sandbox Code Playgroud)


小智 7

非常简单 1)我们使用 arange 函数:-

arr3=np.arange(0,10)
output=array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Run Code Online (Sandbox Code Playgroud)

2)我们使用提供1的ones函数,然后我们将乘以3:-

arr4=np.ones(10)*3
output=array([3., 3., 3., 3., 3., 3., 3., 3., 3., 3.])
Run Code Online (Sandbox Code Playgroud)


New*_*ler 6

另一种(更快)的方法是使用np.empty()and np.fill()

\n
import numpy as np\n\nshape = 10\nvalue = 3\n\n\nmyarray = np.empty(shape, dtype=np.int)\nmyarray.fill(value)\n
Run Code Online (Sandbox Code Playgroud)\n

时间对比

\n

上述方法在我的机器上执行的目的是:

\n
951 ns \xc2\xb1 14 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 1000000 loops each)\n
Run Code Online (Sandbox Code Playgroud)\n

与使用np.full(shape=shape, fill_value=value, dtype=np.int)执行:

\n
1.66 \xc2\xb5s \xc2\xb1 24.3 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 1000000 loops each)\n
Run Code Online (Sandbox Code Playgroud)\n

与使用np.repeat(value, shape)执行:

\n
2.77 \xc2\xb5s \xc2\xb1 41.3 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 100000 loops each)\n
Run Code Online (Sandbox Code Playgroud)\n

与使用np.ones(shape) * value执行:

\n
2.71 \xc2\xb5s \xc2\xb1 56.2 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 100000 loops each)\n
Run Code Online (Sandbox Code Playgroud)\n

我发现它始终快一点。

\n


ben*_*so8 5

我意识到它没有使用 numpy,但这对于基本 python 来说非常容易。

data = [3]*10
print(data)
> [3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
Run Code Online (Sandbox Code Playgroud)