Search code examples
pythonpandasnumpyserieslinspace

How to loop through a series and create a new series based on values from the original series?


I am trying to create a new series that uses entries from a series of two columns. Each column contains a limit, upper and lower and I want to create an array for each entry of the new series.

Series =

lower upper
0 20.20 56.20
1 10.00 77.70

What I want is to use the following code:

np.linsapce(lower,upper,5) 

this creates an array of 5 points, starting from lower number to upper. The new series would look like:

range
0 [20.2, 25.34285714, 30.48571429... 56.2]
1 [10., 19.67142857, 29.34285714... 77.7]

Solution

  • Use apply:

    df['range'] = df.apply(lambda x: np.linspace(x['lower'], x['upper'], 5), axis=1)
    
    >>> df
       lower   upper                                            range
    
    0    20.2   56.2                   [20.2, 29.2, 38.2, 47.2, 56.2]
    1    10.0   77.7  [10.0, 26.925, 43.85, 60.775000000000006, 77.7]