for循环爬取Finviz数据时Pandas如何将DataFrame各列的'-'替换为NaN
核心问题定位
原代码中replace操作不生效的原因非常明确:
- Pandas 的
DataFrame.replace()方法默认非原地修改模式,原写法既没有传入inplace=True参数,也没有手动接收方法返回的新数据帧,循环里执行的df.replace(['-'], np.NaN)没有对原DataFrame做任何实际改动,完全是无效代码。 - 你要求实现边爬边处理,没必要每次循环对全表做替换操作,单条指标值获取完成的瞬间做判断转换,效率更高也更匹配需求。
落地实现方案
直接修改第二层指标循环的写入逻辑,从源头把采集到的'-'字符串转换成空值,完全跳过全表替换的步骤:
- 删除原有无效的
df.replace(['-'], np.NaN)代码行 - 在拿到单条指标返回值、写入DataFrame之前增加判断:
for m in df.columns: output = fundamental_metric(soup, m).strip() # 采集到'-'时直接赋值空值,避免字符串类型进入数据集 if output == '-': df.loc[symbol, m] = np.nan else: df.loc[symbol, m] = output
修正后完整可运行代码
# Import Libraries import pandas as pd from bs4 import BeautifulSoup as bs import requests import numpy as np # For custom list of stocks, edit this list below, otherwise leave commented out stock_list = ['NVAX'] # Header required to scrape from Finviz headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'Upgrade-Insecure-Requests': '1', 'Cookie': 'v2=1495343816.182.19.234.142', 'Accept-Encoding': 'gzip, deflate, sdch', 'Referer': "http://finviz.com/quote.ashx?t="} # This function is what is used to find the metric of interest and return it def fundamental_metric(soup, metric): return soup.find(text=metric).find_next(class_='snapshot-td2').text # This function iterates through the index of the data frame (stock_list) and uses the fundemental_metric functinon to find the metric on Finviz for that stock # Any stock in the list that cannot be scraped will return an error before moving on to the next stock def get_fundamental_data(df): for symbol in df.index: try: 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).strip() # 边采集边替换'-'为null if output == '-': df.loc[symbol,m] = np.nan else: df.loc[symbol,m] = output except Exception as e: print (symbol, 'Not Found') print(e) return df # List of metrics to scrape # Before adding any metrics, ensure the metric being added is available on Finviz and the name is matched identically metric = [ 'Price' , 'Change' , 'Index' ] df = pd.DataFrame(index = stock_list, columns = metric) df = get_fundamental_data(df) print(df)
补充说明:完成上述改造后,所有爬取阶段碰到的
'-'值会被实时转换为真正的空值,不会残留字符串类型标记,后续做浮点型筛选时不会再出现类型不匹配的异常。
内容的提问来源于stack exchange,提问作者MaxDawg27
相关产品推荐
相关产品推荐

