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

Python DataFrame如何计算每行ID对应多列得分的斜率

Pandas 按行计算得分序列斜率实现方案

计算逻辑

对每行ID对应的t1~t4得分,以时间点[1,2,3,4]为x轴、得分为y轴做线性回归,取回归系数作为斜率,计算时自动跳过空值,结果保留1位小数。

完整代码

首先导入依赖库:

import pandas as pd
from scipy.stats import linregress

如果你的环境无法安装scipy,也可以用纯Python手动计算斜率,不需要额外依赖。

步骤1:构造/读取你的DataFrame

这里用你给出的示例数据构造,实际使用时替换为你读取数据的代码即可:

df = pd.DataFrame({
    'ID': ['a', 'b', 'c', 'd', 'e'],
    't1': [1, 3, 4, 2, 0],
    't2': [2, 2, 2, 3, 2],
    't3': [3, 1, 1, 4, 3],
    't4': [4, None, 2, 5, 4]
})

步骤2:定义斜率计算函数

def calc_row_slope(row):
    # 提取当前行的得分,过滤空值
    y_val = row[['t1', 't2', 't3', 't4']].dropna().values
    # 生成对应时间点x值
    x_val = list(range(1, len(y_val)+1))
    # 线性回归计算斜率,保留1位小数
    return round(linregress(x_val, y_val).slope, 1)

不需要依赖scipy的手动实现版本:

def calc_row_slope(row):
    y_val = row[['t1', 't2', 't3', 't4']].dropna().values
    n = len(y_val)
    x_val = list(range(1, n+1))
    sum_x = sum(x_val)
    sum_y = sum(y_val)
    sum_xy = sum([x*y for x,y in zip(x_val, y_val)])
    sum_x_sq = sum([x**2 for x in x_val])
    slope = (n * sum_xy - sum_x * sum_y) / (n * sum_x_sq - sum_x **2)
    return round(slope, 1)

步骤3:应用函数得到结果

# 追加斜率列到原DataFrame
df['Slope'] = df.apply(calc_row_slope, axis=1)
# 如需仅保留ID和斜率列,执行以下代码
result = df[['ID', 'Slope']]
print(result)

输出结果

运行后得到的结果和你预期完全一致:

ID  Slope
0  a    1.0
1  b   -1.0
2  c   -0.7
3  d    1.0
4  e    1.3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 19:18:03