【问题标题】:Excluding Exceptions in Dataframe排除数据框中的异常
【发布时间】:2021-02-03 23:02:44
【问题描述】:

我有一个从 Finviz 抓取数据的函数,该函数的一部分编译了一个指标列表。如果网站地址在遍历股票列表时不存在,它仍会在 Dataframe 中创建一行,其中包含股票名称,但不包含任何指标。我想要这样,如果它找不到该网站,该行要么在循环结束时被删除,要么根本不包括在内。任何有关我如何调整此功能的见解将不胜感激。

def get_fundamental_data(df):
    for symbol in df.index:
        try:
            #url = ("http://finviz.com/quote.ashx?t=" + symbol.lower())
            r = requests.get("http://finviz.com/quote.ashx?t="+ symbol.lower(),headers=headers)
            soup = bs(r.content,'html.parser')
            for m in df.columns:
                output = fundamental_metric(soup,m)
                df.loc[symbol,m] = output
                df = df.replace(['-'], np.NaN)
        except Exception as e:
            print (symbol, 'Not Found')
            print(e)
    return df

【问题讨论】:

    标签: python pandas function dataframe exception


    【解决方案1】:

    一个简单的解决方案是存储发生异常的股票并在循环后删除这些行。删除行将发生在for-loop 之后,以避免在迭代数据帧时更改数据帧。

    def get_fundamental_data(df):
        symbols_to_drop = []
        for symbol in df.index:
            try:
                #url = ("http://finviz.com/quote.ashx?t=" + symbol.lower())
                r = requests.get("http://finviz.com/quote.ashx?t="+ symbol.lower(),headers=headers)
                soup = bs(r.content,'html.parser')
                for m in df.columns:
                    output = fundamental_metric(soup,m)
                    df.loc[symbol,m] = output
                    df = df.replace(['-'], np.NaN)
            except Exception as e:
                symbols_to_drop.append(symbol)
                print (symbol, 'Not Found')
                print(e)
        df = df.drop(symbols_to_drop)
        return df
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-24
      • 1970-01-01
      • 1970-01-01
      • 2017-10-26
      • 2018-03-23
      • 2023-03-11
      • 2018-12-16
      相关资源
      最近更新 更多