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

Pandas DataFrame中计算每日数值与7天前数据比值的实现方法

正确实现代码

首先先确保你的DataFrame按日期升序排列(你给出的示例数据已经是升序,保险起见加上排序逻辑):

# 按日期升序排序,保证行顺序从早到晚
df = df.sort_index(ascending=True)
# 计算向上偏移7行的历史值
df['history_7d'] = df['totale_positivi'].shift(periods=7)
# 计算比值,空值(没有7天前对应值的行)填充为1,转整数符合你的示例输出
df['totale_positivi'] = df['totale_positivi'].div(df['history_7d']).fillna(1).astype(int)
# 删除临时计算列
df = df.drop(columns=['history_7d'])

原有写法错误原因

  • 第一种循环写法:
    1. 循环逻辑错误,while(i>7)没有修改i值的逻辑,会进入死循环
    2. loc索引使用错误,df.loc['totale_positivi']是查询索引为字符串'totale_positivi'的行,不是对列赋值
    3. 没有实现空值默认填1的逻辑
  • 第二种写法:
    div()是pandas的除法方法,本身不支持periods参数,需要先调用shift()方法获取偏移7行的历史值再做除法运算。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 08:15:03