You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas DataFrame除法遇ZeroDivisionError:如何让分母为0时返回NaN?

Fixing ZeroDivisionError in Your ROIC Calculation Function

Hey there, let's sort out that ZeroDivisionError you're hitting in your get_roic function. The issue with your modified version is likely that your where condition might not be catching all zero values (for example, if your denominator is integer type instead of float, checking against 0.0 won't match integer 0), or the division is still trying to process the zero before the where takes effect.

Here are two reliable solutions to handle division by zero and return NaN instead of throwing an error:

Solution 1: Use pandas' divide with errors='coerce'

Pandas' divide method has a built-in errors parameter that lets you automatically convert division errors (like division by zero) to NaN. This is the cleanest approach:

import pandas as pd
import numpy as np

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'])
    # Use errors='coerce' to turn division errors into NaN
    table['roic'] = table['fcf'].divide(table['Invested Capital'], errors='coerce')
    table['revenue'] = IC.loc['revenue']
    table['fcf/revenue'] = table['fcf'].divide(table['revenue'], errors='coerce')
    return table

Solution 2: Explicitly Check for Zeros with np.where

If you prefer a more explicit approach, use numpy.where to conditionally compute the division only when the denominator isn't zero:

import pandas as pd
import numpy as np

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'])
    # Return NaN when denominator is 0, else compute the ratio
    table['roic'] = np.where(table['Invested Capital'] == 0, np.nan, table['fcf'] / table['Invested Capital'])
    table['revenue'] = IC.loc['revenue']
    table['fcf/revenue'] = np.where(table['revenue'] == 0, np.nan, table['fcf'] / table['revenue'])
    return table

Why Your Original Modified Version Failed

The problem with your initial fix was probably a type mismatch: if your Invested Capital or revenue columns are integer types, checking against 0.0 (a float) won't match integer 0 values. So the where method wasn't replacing those zeros with NaN, leading to the same division error. Using == 0 instead of == 0.0 would have fixed that, but the solutions above are more robust.

内容的提问来源于stack exchange,提问作者Ben2pop

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 15:22:53