a = []
for j in range(1000):
a.append(sample_function(x))
a = np.array(a)
What is the proper and elegant way to replace this code? I don't work working with python list is optimal.
CodePudding user response:
If we assume sample_function(x)
is a scaler, you can use:
a = np.full(shape=1000, sample_function(x)) # or smth like --> np.full((1, 1000), sample_function(x))
but if you have an array that you would to apply a function on all of the elements:
a = np.apply_along_axis(sample_function, axis, arr) # or --> np.apply_over_axes
CodePudding user response:
You can do:
a = example_function(np.arange(1000))
where example_function
is arbitrary, i.e.:
def example_function(x):
return x**2
CodePudding user response:
It looks like you want to create a numpy array using values from a function.
You could try using np.fromfunction like this:
import random # for example sample function
def sample_function(_):
return random.random() * 42
a = np.fromfunction(np.vectorize(sample_function), (1000, ))
If you want sample_function
to calculate values depending on the coordinates then this is also straight forward:
def sample_function(i):
return random.random() * i
CodePudding user response:
just use:
a=np.arange(0,1000,1)