Skip to content Skip to sidebar Skip to footer

Using Numpy.rate, On Numpy Array Returns Nan's Unexpectedly

I'm using np.rate function to calculate simple growth rates. I'm trying to use vector operations. This works: b = np.arange(1,10) np.rate(1,0,-b[:-1],b[1:]) This returns: array([

Solution 1:

Your second case has a zero in b.

np.rate can't handle a 0 value there.

As well as I can understand from the (brief) documentation of np.rate, you're asking it to find what interest rate is needed to turn 0 into 1 in a single pay period. This is a challenging problem you're asking it to solve.

To fix it, you simply need to not have a 0 there.

Solution 2:

I can think of two potential workarounds.

(1) store -b[:-1] and b[1:] in a pandas DataFrame, and use .apply to calculate np.rate for each row. This will be slower than the vectorised approach in your example.

import pandas as pd
import numpy as np
import numpy_financial as npf # I get a warning telling me to use numpy_financial instead of numpy
b = np.arange(0,10)
df = pd.DataFrame({'a':-b[:-1],'b':b[1:]})
res = df.apply(lambda x: npf.rate(1,0,x.a,x.b),axis=1)
# [nan,0.9999999999999999, 0.4999999999999999, 0.33333333333333326, 0.24999999999999992, 0.2, 0.1666666666666667, 0.1428571428571427, 0.12499999999999992]

(2) Store in a Pandas dataframe, and add a filter for the entries being valid. In your example, nper > 0 but in other cases you would also want to filter for other criteria, such as (pmt * npt) >= pv.

valid_df = df.loc[df['a'] !=0] # in real examples add other filtering here.

You can then use the vectorised calculation only on these filtered rows.

df['result'] = np.nan
df.loc[df['a'] != 0,'result'] = npf.rate(1,0,valid_df.a,valid_df.b)

Post a Comment for "Using Numpy.rate, On Numpy Array Returns Nan's Unexpectedly"