I am trying to eliminate an inf from a pandas DataFrame, caused by a division by zero. I have tried several techniques using both DataFrame and ndarray structures:
df_fund['dly_retn'].replace(np.inf, 0)
na_fund['dly_retn'].replace(np.inf, 0)
na_dly_retn(~isfinite(na_dly_retn))=0
Taking the mean in every case results in "inf"
I have searched for two days without finding an answer to what should be a trivial problem.
What is this? Notice that each of the inf and -inf values have been replaced with zero.
Use np. nan_to_num() replace NaN values with zeroes Call np. nan_to_num(x) to replace every instance of NaN in array x with 0 .
nan_to_num() function is used when we want to replace nan(Not A Number) with zero and inf with finite numbers in an array. It returns (positive) infinity with a very large number and negative infinity with a very small (or negative) number.
you can do it for an entire dataframe as follow:
new_df.replace(np.inf, 0, inplace=True)
You have to save the operation in your dataframe. One way is to use the parameter inplace=True
:
df_fund['dly_retn'].replace(np.inf, 0, inplace=True)
na_fund['dly_retn'].replace(np.inf, 0, inplace=True)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With