简体   繁体   中英

Creating a function in Python which runs over a range and returns a new value to an array each time

Basically, what I'm trying to create is a function which takes an array, in this case:

numpy.linspace(0, 0.2, 100)

and runs a lot of other code for each of the elements in the array and at the end creates a new array with one a number for each of the calculations for each element. A simple example would be that the function is doing a multiplication like this:

def func(x):
   y = x * 10
   return (y)

However, I want it to be able to take an array as an argument and return an array consisting of each y for each multiplication. The function above works for this, but the one I've tried creating for my code doesn't work with this method and only returns one value instead. Is there another way to make the function work as intended? Thanks for the help!

Maybe take a look at np.vectorize :

https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.vectorize.html

np.vectorize can for example be used as a decorator:

  @np.vectorize
  def func(value):
     ...
     return return_value

The function to be vectorized (here func ) has to be a function, that takes a value as input and returns a value. This function then gets vectorized over the whole array.

It is mentioned in the documentation, but it cant hurt to emphasize it here: In general this function is only used for convenience not for performance, it is basically equivalent to using a for-loop.

If you are able to build up your function from numpys ufuncs like ( np.add , np.mean , etc.) this will likely be much faster. Or you could write your own:
https://docs.scipy.org/doc/numpy-1.13.0/reference/ufuncs.html

You could use this simple code:

def func(x):
    y = []
    for i in x:
        y.append(i*10)
    return y

You can do this with numpy already with your function. For example, the code below will do what you want:

x = numpy.linspace(0, 0.2, 100)
y = x*10

If you defined x as above and passed it to your function it would perform exactly as you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM