Example:
n = 5
x = 3.5
Output:
array([3.5, 3.5, 3.5, 3.5, 3.5])
My code:
import numpy as np
def init_all_x(n, x):
np.all = [x]*n
return np.all
init_all_x(5, 3.5)
My question:
Why init_all_x(5, 3.5).shape cannot run?
If my code is wrong, what is the correct code? Thank you!
CodePudding user response:
you can use np.ones
arr = np.ones(5)*3.5
CodePudding user response:
Simple approach with numpy.repeat
:
n = 5
x = 3.5
a = np.repeat(x, n)
Output:
array([3.5, 3.5, 3.5, 3.5, 3.5])
CodePudding user response:
For your requirement, no need to use Numpy lib
, you can code like this:
def init_all_x(n, x):
return [x]*n
p = init_all_x(5, 3.5)
print(p)
Output:
[3.5, 3.5, 3.5, 3.5, 3.5]
CodePudding user response:
Numpy has a dedicated function np.full
to do just this:
n = 5
x = 3.5
out = np.full(n, x)
# array([3.5, 3.5, 3.5, 3.5, 3.5])