Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace inf in a numpy array with zero

Tags:

pandas

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.

like image 697
Drew Yallop Avatar asked Nov 21 '16 00:11

Drew Yallop


People also ask

What can I replace INF with?

What is this? Notice that each of the inf and -inf values have been replaced with zero.

How do you replace all missing values with 0 in a NumPy array?

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 .

How do you replace NaN with 0 in an array?

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.


2 Answers

you can do it for an entire dataframe as follow:

new_df.replace(np.inf, 0, inplace=True)
like image 93
Joselin Ceron Avatar answered Dec 16 '22 18:12

Joselin Ceron


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)
like image 28
Zeugma Avatar answered Dec 16 '22 18:12

Zeugma