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

如何为以Date为索引的DataFrame添加新日期索引及Volume值?

实现方案

首先要确保你的DataFrame索引(Date列)是datetime64类型,否则无法进行日期运算。如果当前索引不是该类型,先执行转换:

import pandas as pd
df.index = pd.to_datetime(df.index)

方法一:使用pd.concat(推荐,兼容pandas新版本)

这种方法可明确构建新行,避免append方法的弃用警告:

# 获取最后一个索引日期并计算新日期
last_date = df.index[-1]
new_date = last_date + pd.Timedelta(days=7)

# 创建包含新数据的单行DataFrame
new_row = pd.DataFrame({'Volume': [39]}, index=[new_date])

# 合并到原DataFrame
df = pd.concat([df, new_row])

方法二:使用loc直接赋值(简洁高效)

如果仅需追加单行,直接通过索引赋值更快捷:

last_date = df.index[-1]
new_date = last_date + pd.Timedelta(days=7)

# 直接给新索引对应的Volume列赋值
df.loc[new_date, 'Volume'] = 39

注意事项

  • 如果原DataFrame包含除Volume外的其他列,使用loc方法时,新行的其他列会被填充为NaN;若需要设置默认值,可在赋值时一并指定,比如df.loc[new_date, ['Volume', 'OtherCol']] = [39, 0]。
  • 务必保证索引为datetime类型,否则日期加法会抛出类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 09:55:09