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

Pandas如何将另一DataFrame的最后索引值添加到空DataFrame

错误原因
  • 执行df_pnl.index[0:] = df_chosen_trading_pair.index[-1]报错,是因为Pandas的Index对象是不可变类型,不支持通过切片赋值的方式直接修改索引元素,因此触发可变操作相关的类型错误。
  • 执行df_pnl["End Date"][-1] = df_chosen_trading_pair.index[-1]报错,是因为End Date是df_pnl的索引名称,并不是DataFrame中存储的列,直接按列名访问自然会触发键错误。
实现方法

使用loc索引器追加新行即可,当loc指定的索引值不存在时,Pandas会自动新增对应索引的行,未手动赋值的字段会默认填充NaN,和预期输出完全一致:

# 提取需要的最后一个时间索引
target_date = df_chosen_trading_pair.index[-1]
# 追加对应索引的新行
df_pnl.loc[target_date, :] = None

执行后打印df_pnl就能得到目标结果:

PnL  Type of Trade  ROI  Cumulative ROI  Cumulative Investment
End Date                                                                             
2022-06-27 06:59:59.999  NaN            NaN  NaN             NaN                    NaN

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 16:57:48