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

如何在原始Pandas DataFrame中插入行差值数据

问题描述

我通过pd.read_csv读取的DataFrame每次运行脚本都会新增一行数据,原始数据样例如下:

import pandas as pd

df = pd.read_csv(file_path)
print(df.to_string(index=False))

输出:

timestamp    Puts   Calls  PutCh  CallCh  ChDiff
09:41:12 AM 2027891 1820724 280101  200974   79127
09:48:51 AM 2075976 1862053 328186  242303   85883
09:58:48 AM 2091487 1885842 343697  266092   77605
10:08:21 AM 2091879 1918592 344089  298842   45247
02:26:00 PM 1995234 1941917 247444  322167  -74723
02:44:36 PM 1990071 1934874 242281  315124  -72843
02:56:17 PM 1970892 1938472 223102  318722  -95620

我先删除timestamp列得到df1,用df1.diff()计算每行与前一行的差值,结果如下:

Puts   Calls    PutCh  CallCh    ChDiff
     NaN     NaN      NaN     NaN       NaN
 48085.0 41329.0  48085.0 41329.0    6756.0
 15511.0 23789.0  15511.0 23789.0   -8278.0
   392.0 32750.0    392.0 32750.0  -32358.0
-96645.0 23325.0 -96645.0 23325.0 -119970.0
 -5163.0 -7043.0  -5163.0 -7043.0    1880.0
-19179.0  3598.0 -19179.0  3598.0  -22777.0

现在需要把这些差值以括号包裹的形式插入原始DataFrame的对应行下方,同时保留timestamp列,最终输出样式如下(示例简化了部分行):

timestamp    Puts    Calls   PutCh   CallCh  ChDiff
09:41:12 AM 2027891 1820724 280101  200974  79127
09:48:51 AM 2075976 1862053 328186  242303  85883
            (48085) (41329) (48085) (41329) (6756)
09:58:48 AM 2091487 1885842 343697  266092  77605
            (15511) (23789) (15511) (23789) (-8278)
10:08:21 AM 2091879 1918592 344089  298842  45247
            (392)   (32750) (392)   (32750) (-32358)
解决方案

可以通过以下步骤实现需求:

  1. 计算差值并格式化
    先计算差值,再把数值转换成带括号的字符串,同时处理第一行的NaN(第一行无前置行,差值行留空):

    import pandas as pd
    
    # 读取原始数据
    df = pd.read_csv(file_path)
    # 计算差值,排除timestamp列
    diff_df = df.drop('timestamp', axis=1).diff()
    # 将数值转为带括号的字符串,NaN转为空字符串
    diff_formatted = diff_df.applymap(lambda x: f'({int(x)})' if pd.notna(x) else '')
    # 给差值行的timestamp列填充空字符串,对齐原始数据格式
    diff_formatted.insert(0, 'timestamp', '')
    
  2. 合并原始行与差值行
    把原始DataFrame和格式化后的差值DataFrame按行交替拼接:

    # 创建空列表存储结果行
    result_rows = []
    # 遍历原始行和差值行,交替添加
    for idx, orig_row in df.iterrows():
        result_rows.append(orig_row.tolist())
        # 跳过第一行的差值(无前置行)
        if idx > 0:
            result_rows.append(diff_formatted.iloc[idx].tolist())
    # 转换为最终DataFrame
    final_df = pd.DataFrame(result_rows, columns=df.columns)
    
  3. 输出结果
    打印最终的DataFrame,去掉索引:

    print(final_df.to_string(index=False))
    

执行上述代码后,就能得到符合要求的输出:原始数据行下方紧跟带括号的差值行,timestamp列在差值行留空对齐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 14:20:35