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

如何用For Loop基于现有数据向Pandas DataFrame追加行

基于Pandas DataFrame循环追加新行的实现方法

现有代码与初始数据

生成包含GMV、differences和percentage列的初始DataFrame代码:

monthly['differences'] = monthly.GMV.diff()
monthly['percentage'] = monthly.differences / (monthly.GMV - monthly.differences) *100
monthly

生成的初始DataFrame:

GMV         differences percentage
date            
1   69793.30    NaN         NaN
2   65159.60    -4633.70    -6.639176
3   70397.10    5237.50     8.037956
4   68736.80    -1660.30    -2.358478
5   71402.75    2665.95     3.878490
6   68230.20    -3172.55    -4.443176
7   72557.90    4327.70     6.342792
8   68278.25    -4279.65    -5.898255
9   64180.05    -4098.20    -6.002204
10  64027.60    -152.45     -0.237535
11  70395.35    6367.75     9.945320
12  64701.15    -5694.20    -8.088887

需求说明

需通过循环基于现有数据追加新行,计算规则如下(以第13行为例):

  • GMV13 = GMV12 + (GMV12 × percent12 / 100)(注意percent为百分比数值,需除以100转换为比例)
  • diff13 = GMV13 - GMV12
  • percent13 = (diff13 / GMV12) × 100(原规则公式存在错误,此处修正为与初始列计算逻辑一致的公式)

后续第14行及之后行均按此规则生成。

实现代码

通过循环迭代获取最后一行数据,计算新行后追加到DataFrame中:

import pandas as pd

# 设定需要追加的行数,示例中需追加7行到第19行
num_rows_to_add = 7

for _ in range(num_rows_to_add):
    # 获取DataFrame最后一行数据
    last_row = monthly.iloc[-1]
    last_gmv = last_row['GMV']
    last_percent = last_row['percentage']
    
    # 计算新行的三个字段值
    new_gmv = last_gmv + (last_gmv * last_percent / 100)
    new_diff = new_gmv - last_gmv
    new_percent = (new_diff / last_gmv) * 100
    
    # 创建新行,索引为当前最大索引+1
    new_index = monthly.index.max() + 1
    new_row = pd.Series(
        data=[new_gmv, new_diff, new_percent],
        index=['GMV', 'differences', 'percentage'],
        name=new_index
    )
    
    # 将新行追加到原DataFrame(Pandas 2.0+推荐用_append,旧版本用append)
    monthly = monthly._append(new_row)

# 可选:重置索引并保持date列为索引
monthly = monthly.reset_index(drop=False).rename(columns={'index': 'date'}).set_index('date')

关键说明

  • 原规则中的percent13= diff13 / (GMV13 * diff13) * 100公式有误,计算结果为100/GMV13,与初始percentage的计算逻辑矛盾,因此修正为和初始列一致的计算方式。
  • 若需要追加更多行,只需调整num_rows_to_add的数值即可。
  • 运行代码后,生成的DataFrame将与用户提供的演示示例结构、数值逻辑一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 13:15:40