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

如何用Pandas实现DataFrame首行与列内其余行的差值计算及表达式生成

Pandas实现首行运算式列与差值计算方案

首先看原始数据集:

import pandas as pd
df = pd.DataFrame([
    [1, 4],
    [4, 6],
    [8, 2],
    [0, 8]
], columns=['a', 'b'])

一、生成运算式字符串列

对每一列生成格式为首行值-当前行值的字符串列,命名为operation_on_列名,直接通过apply结合字符串格式化实现:

# 遍历列生成运算式列
for col in df.columns:
    first_val = df[col].iloc[0]
    df[f'operation_on_{col}'] = df[col].apply(lambda x: f"{first_val}-{x}")

执行后DataFrame会新增对应列,比如operation_on_a列内容为'1-1'、'1-4'、'1-8'、'1-0',operation_on_b列对应为'4-4'、'4-6'、'4-2'、'4-8'。

二、计算首行与各行的差值结果表

利用Pandas的广播特性,直接用首行数据减去整个DataFrame即可得到差值表:

# 计算首行与所有行的差值
diff_result = pd.DataFrame(df.iloc[0] - df, columns=df.columns)

得到的diff_result结果如下:

ab
00
-3-2
-72
1-4

完整合并方案

如果需要同时保留原始列、运算式列和差值列,可以将差值列合并到原DataFrame中:

import pandas as pd
df = pd.DataFrame([
    [1, 4],
    [4, 6],
    [8, 2],
    [0, 8]
], columns=['a', 'b'])

# 生成运算式列
for col in df.columns:
    first_val = df[col].iloc[0]
    df[f'operation_on_{col}'] = df[col].apply(lambda x: f"{first_val}-{x}")

# 计算差值并合并到原表
diff_result = pd.DataFrame(df.iloc[0] - df, columns=df.columns)
diff_result.columns = [f'diff_{col}' for col in diff_result.columns]
df = pd.concat([df, diff_result], axis=1)

print(df)

输出结果:

a  b operation_on_a operation_on_b  diff_a  diff_b
0  1  4           1-1           4-4       0       0
1  4  6           1-4           4-6      -3      -2
2  8  2           1-8           4-2      -7       2
3  0  8           1-0           4-8       1      -4

不需要用到NumPy的triu_indices,Pandas自带的索引和广播机制完全可以覆盖本次需求的按列运算场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 00:27:38