Ben2pop
Ben2pop

Reputation: 756

ZeroDivisionError: float division by zero on a pandas dataFrame

I have a function that run over dataFrames and do some manipulations such as division, My issues is that some of the values are 0 and I get an error ZeroDivisionError: float division by zero

my goal that if I have a 0 as denominator it return Nan my function look like this:

def get_roic(BS, KPI, IC):
     table = KPI.loc['fcf'].to_frame('fcf')
     table['Invested Capital'] = (BS.loc['st_debt'] + BS.loc['other_current_liabilities'] + 
     BS.loc['lt_debt'] + BS.loc['other_lt_liabilities'] + BS.loc['total_equity'])
     table['roic'] = table['fcf'].divide(table['Invested Capital'])
     table['revenue'] = IC.loc['revenue']
     table['fcf/revenue'] = table['fcf'].divide(table['revenue'])    
     return table

I tried many things such as:

def get_roic(BS, KPI, IC):
    table = KPI.loc['fcf'].to_frame('fcf')
    table['Invested Capital'] = (BS.loc['st_debt'] + BS.loc['other_current_liabilities'] + BS.loc['lt_debt'] + BS.loc['other_lt_liabilities'] + BS.loc['total_equity'])
    table['roic'] = table['fcf'].divide(table['Invested Capital'].where(table['Invested Capital'] != 0.0, np.nan))
    table['revenue'] = IC.loc['revenue']
    table['fcf/revenue'] = table['fcf'].divide(table['revenue'].where(table['revenue'] != 0.0, np.nan))     
    return table

But I do not get to make it work .. any ideas ?

Upvotes: 0

Views: 3966

Answers (1)

NYC Coder
NYC Coder

Reputation: 7594

Have you tried this:

df['fcf/revenue'] = df['fcf'].divide(df['revenue']) 
df['fcf/revenue'] = df['fcf/revenue'].replace(np.inf, np.nan)

   a   fcf  revenue  fcf/revenue
0  1  23.0     45.0     0.511111
1  2  34.0     56.0     0.607143
2  3  23.0      0.0          NaN

Upvotes: 0

Related Questions