尝试,捕捉,除了在数据框中

Try, catch, except in a dataframe

我想在这段代码中计算某些比率并将结果放入 DataFrame 中。由于我正在抓取的语句不统一,一些变量可能会丢失并导致 KeyErrors 或 TypeErrors。我要做的只是用“Error.”替换错误发生的位置。

我目前的编码方式导致整行显示“错误”。

这是我的代码:

try:
    Ratio_df.loc[stock] = [stock, beta, dividendYield, (sharesOutstanding*close_price_num)/1000000000,
                           '{:.2f}'.format(close_price_num), (close_price_num/earnings/1000),
                           (EV/(final_df.at['Total Revenue', 'ttm'])/1000), close_price_num/EE, EV/RE,
                           float('{:.1f}'.format((RE/(final_df.at['Total Revenue', 'last year']*1000) - 1)*100)), EV/final_df.at['Normalized EBITDA', 'ttm']/1000,
                           EV/1000000000, '{:.1f}'.format((FCF/(final_df.at['Total Revenue', 'ttm'])/10)),
                           '{:.1f}'.format(final_df.at['Normalized EBITDA', 'ttm']/final_df.at['Total Revenue', 'ttm']*100),
                           (EV/(final_df.at['Normalized EBITDA', 'last year'] * (1 + (RE/(final_df.at['Total Revenue', 'last year']) - 1)))), '-']
except KeyError:
        Ratio_df.loc[stock] = 'Error'

结果如下: Output

感谢您的帮助!如果您需要更多信息,请告诉我。

按照目前的编写方式,您将在第一个错误时中止整行计算,因此即使您确实知道错误的位置,也无法继续进行下一次计算。相反,您可以用 try-catch 包装每个计算,如果发生错误,则将 g 放置在 "Error" 字符串中。最好用一个函数来包装它。例如,我创建了一个玩具数据集,因为从你的问题中复制是不可能的:

from typing import Callable, Union

def compute_or_error(action: Callable) -> Union[float, str]:
    try:
        return action()
    except KeyError:
        return "Error"


df = pd.DataFrame({"A": list(range(3)), "B": list(range(1, 4))})
i = 0
df.loc[i] = [compute_or_error(lambda: df["B"][i] / df["C"][i]), df["B"][i] + df["A"][i]]
print(df)

结果如下:

       A  B
0  Error  1
1      1  2
2      2  3

修改您的代码后,它看起来像这样:

Ratio_df.loc[stock] = [
    stock,
    beta,
    dividendYield,
    compute_or_error(lambda: (sharesOutstanding * close_price_num) / 1000000000),
    compute_or_error(lambda: round(close_price_num, 2)),
    compute_or_error(lambda: close_price_num / earnings / 1000),
    compute_or_error(lambda: EV / (final_df.at['Total Revenue', 'ttm']) / 1000),
    compute_or_error(lambda: close_price_num / EE),
    compute_or_error(lambda: EV / RE),
    compute_or_error(lambda: round((RE / (final_df.at['Total Revenue', 'last year'] * 1000) - 1) * 100, 1)),
    compute_or_error(lambda: EV / final_df.at['Normalized EBITDA', 'ttm'] / 1000),
    compute_or_error(lambda: EV / 1000000000),
    compute_or_error(lambda: round(FCF / (final_df.at['Total Revenue', 'ttm']) / 10, 1)),
    compute_or_error(
        lambda: round(final_df.at['Normalized EBITDA', 'ttm'] / final_df.at['Total Revenue', 'ttm'] * 100, 1)),
    compute_or_error(lambda: EV / (final_df.at['Normalized EBITDA', 'last year'] * (
            1 + (RE / (final_df.at['Total Revenue', 'last year']) - 1)))),
    '-']

您没有提供原始数据集来检查解决方案,但它应该可以工作