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)
用途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)
另一种(更快)的方法是使用np.empty()and np.fill():
import numpy as np\n\nshape = 10\nvalue = 3\n\n\nmyarray = np.empty(shape, dtype=np.int)\nmyarray.fill(value)\nRun Code Online (Sandbox Code Playgroud)\n时间对比
\n上述方法在我的机器上执行的目的是:
\n951 ns \xc2\xb1 14 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 1000000 loops each)\nRun Code Online (Sandbox Code Playgroud)\n与使用np.full(shape=shape, fill_value=value, dtype=np.int)执行:
1.66 \xc2\xb5s \xc2\xb1 24.3 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 1000000 loops each)\nRun Code Online (Sandbox Code Playgroud)\n与使用np.repeat(value, shape)执行:
2.77 \xc2\xb5s \xc2\xb1 41.3 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 100000 loops each)\nRun Code Online (Sandbox Code Playgroud)\n与使用np.ones(shape) * value执行:
2.71 \xc2\xb5s \xc2\xb1 56.2 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 100000 loops each)\nRun Code Online (Sandbox Code Playgroud)\n我发现它始终快一点。
\n我意识到它没有使用 numpy,但这对于基本 python 来说非常容易。
data = [3]*10
print(data)
> [3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
Run Code Online (Sandbox Code Playgroud)