Iterating over a numpy array with enumerate like f

2019-08-10 21:12发布

问题:

I want to numpy arrays into some of my code. I am trying to iterate over an array.

import numpy as np

a=10.0
b=55.0

y=np.asarray([11,30,54,7,22,5,15,65,15,6])

I =[y[i] / (a + (i+1) * b) for i in range(0, len(y))]

print I

>>> 
[0.16923076923076924, 0.25, 0.30857142857142855, 0.030434782608695653, 0.077192982456140355, 0.014705882352941176, 0.037974683544303799, 0.14444444444444443, 0.029702970297029702, 0.010714285714285714]

So far I switched the iteration method to enumerate which will give the same results but with faster speed

J=[y[i] / (a + (i+1) * b) for i, item in enumerate(y)]

print J

In Python pandas there is a function to create an array of [1,2,3,4,5,6,...n] and then using the values in the array instead of using a for loop. Is this available in numpy and does it make the process faster?

回答1:

You can do it without loop with np.arange:

>>> c = a + b*(np.arange(1, len(y)+1))
>>> y/c
array([ 0.16923077,  0.25      ,  0.30857143,  0.03043478,  0.07719298,
        0.01470588,  0.03797468,  0.14444444,  0.02970297,  0.01071429])