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

如何在Pandas DataFrame中按E分组计算含p²因子的数值积分?

解决方案

核心思路是先对每行数据计算p² * S的元素级乘积,再按E分组求和,以此完成离散场景下积分的近似计算。以下是几种优雅的实现方式:

基础实现(带中间列)

  1. 数据格式修正(可选):先确保E和p为数值类型,处理示例中类似.1.、15.的格式问题:
import pandas as pd

# 假设你的DataFrame名为df
df['E'] = df['E'].str.strip('.').astype(float)
df['p'] = df['p'].str.strip('.').astype(float)
  1. 计算乘积列并分组求和:
# 新增列存储p²*S的结果
df['p2_S'] = df['p'] ** 2 * df['S']
# 按E分组求和得到n(E)
n_E = df.groupby('E')['p2_S'].sum().reset_index(name='n(E)')

链式写法(无中间列)

用assign方法合并步骤,避免创建临时列:

n_E = df.assign(p2_S=lambda x: x['p']**2 * x['S'])\
         .groupby('E')['p2_S']\
         .sum()\
         .reset_index(name='n(E)')

精确数值积分(梯形法则)

如果需要更严谨的积分计算,可结合scipy的梯形积分函数:

from scipy.integrate import trapz

def calc_integral(group):
    # 按p排序保证积分顺序正确
    sorted_group = group.sort_values('p')
    return trapz(sorted_group['p']**2 * sorted_group['S'], x=sorted_group['p'])

n_E = df.groupby('E').apply(calc_integral).reset_index(name='n(E)')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 14:52:44