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

咨询:获取标普500公司2016-2021年ESG总分的代码实现方案

解决标普500公司2016-2021年ESG总分获取问题

1. 原代码的核心问题

  • df.append()已被pandas废弃,应使用pd.concat()合并数据
  • 未处理无ESG数据、网络请求失败等异常情况,会导致程序中断
  • 未筛选2016-2021年的目标时间范围

2. 完整改进代码

import pandas as pd
import yesg
from requests.exceptions import RequestException

# 初始化结果存储容器
result_df = pd.DataFrame()

# 获取标普500股票代码列表
sp500_list = pd.read_html('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')[0]
tickers = sp500_list['Symbol'].tolist()

# 遍历每个股票代码
for ticker in tickers:
    try:
        # 获取历史ESG数据
        esg_raw = yesg.get_historic_esg(ticker)
        # 提取总分并筛选2016-2021年的数据
        total_score = esg_raw['Total-Score'].loc['2016-01-01':'2021-12-31']
        # 重命名列名为股票代码,便于合并
        total_score = total_score.rename(ticker)
        # 合并到主DataFrame
        result_df = pd.concat([result_df, total_score], axis=1)
    except RequestException:
        print(f"网络错误:无法获取{ticker}的ESG数据")
    except KeyError:
        print(f"{ticker}无ESG总分数据")
    except Exception as e:
        print(f"处理{ticker}时出错:{str(e)}")

# 转置数据结构,每行对应一家公司
result_df = result_df.T.reset_index().rename(columns={'index': 'Symbol'})

3. 数据缺失处理建议

  • 用result_df.isnull().sum()查看各时间段的缺失数据量
  • 根据需求填充缺失值:
    • 向前填充:result_df.fillna(method='ffill', axis=1)
    • 用0填充:result_df.fillna(0, axis=1)
  • 保存结果到本地:result_df.to_csv('sp500_esg_2016-2021.csv', index=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 20:27:35