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

如何用循环正确填充pandas DataFrame 解决列值被最后遍历项覆盖问题

问题根因

代码存在两个问题导致结果不符合预期:

  • 赋值逻辑错误:每次循环执行Target_Frame["Price"] = current_price时,是给Price列的所有行统一设置为当前单只股票的价格,而非给对应股票的行单独赋值。循环执行到最后一只股票JNJ时,整列值就会全部被JNJ的价格覆盖。
  • 变量名不匹配:循环遍历使用的Equities_List和前面定义的股票列表变量Target_Equities_List名称不一致,直接运行会触发名称错误。
修复代码

通过loc方法按行索引给对应股票的单元格单独赋值即可,修正后的可运行代码:

import pandas as pd
from yahoofinancials import YahooFinancials

Target_Equities_List = ["MSFT", "K", "JNJ"]
Target_Frame = pd.DataFrame(index=Target_Equities_List)
Target_Frame["Price"] = None

for ticker in Target_Equities_List:
    yahoo_financials = YahooFinancials(ticker)
    json_obj_price = yahoo_financials.get_stock_price_data()
    current_price = json_obj_price[ticker]['regularMarketPrice']
    # 仅给当前ticker对应的行的Price列赋值
    Target_Frame.loc[ticker, "Price"] = current_price

运行后输出(价格为拉取时刻的实时值,示例仅供参考):

Price
MSFT  427.19
K      58.67
JNJ   178.29
优化写法

YahooFinancials原生支持传入股票列表批量拉取数据,无需写循环逐只请求,执行效率更高:

Target_Equities_List = ["MSFT", "K", "JNJ"]
yahoo_financials = YahooFinancials(Target_Equities_List)
all_price_data = yahoo_financials.get_stock_price_data()

Target_Frame = pd.DataFrame.from_dict(
    {t: {"Price": d["regularMarketPrice"]} for t, d in all_price_data.items()},
    orient="index"
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.04 16:15:42