-1

I am doing division of column A by column B. Certain places where denominator is 0, I get inf values. How do I replace these inf values with 1 from column C?

Df['C'] = Df['A'] / Df['B']
Ashwin J
  • 9
  • 4
  • You want to remove the whole row, or replace the infinity with something else? – Barmar Apr 03 '20 at 18:43
  • Does this answer your question? [Replacing few values in a pandas dataframe column with another value](https://stackoverflow.com/questions/27060098/replacing-few-values-in-a-pandas-dataframe-column-with-another-value) – Aven Desta Apr 03 '20 at 19:21
  • Thanks Baby Desta. Your comment was helpful. – Ashwin J Apr 07 '20 at 15:58

2 Answers2

0

Try the following:

import numpy as np
Df = Df[Df.C != np.inf]

Edit:

To replace all np.inf values by 1, use this code:

Df.loc[Df.C == np.inf] = 1

Alternatively, you can use pandas.DataFrame.replace() method like this:

Df['C'] = Df['C'].replace({np.inf: 1})
Jaroslav Bezděk
  • 6,967
  • 6
  • 29
  • 46
0
df['C'] = df['A'].div(df['B']) # div will replace inf with null
filt = df['C'].notna() # a filter for not null
df = df.loc[filt] # the new dataframe with no null
Aven Desta
  • 2,114
  • 12
  • 27