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

使用Pandas实现数据操作:首尾对应行平均值计算

问题与需求

已整理好如下数据:

AB
01
12
23
34
45
56
67
78
89
90
10
129
118
107
96
85
74
63
52
41
31
23
15
07

需要生成两列新数据:

  • 新A列:原A列第1行与最后1行的平均值、第2行与倒数第2行的平均值……依次配对计算
  • 新B列:按相同规则计算对应行的平均值
实现方案(Python pandas)

完全可以实现,以下是具体代码:

import pandas as pd

# 构建原始数据框
data = {
    'A': [0,1,2,3,4,5,6,7,8,9,1,12,11,10,9,8,7,6,5,4,3,2,1,0],
    'B': [1,2,3,4,5,6,7,8,9,0,0,9,8,7,6,5,4,3,2,1,1,3,5,7]
}
df = pd.DataFrame(data)

# 计算首尾配对的平均值
half_rows = len(df) // 2
first_part = df.iloc[:half_rows]
second_part = df.iloc[-half_rows:].reset_index(drop=True)

result = pd.DataFrame({
    '新A': (first_part['A'] + second_part['A']) / 2,
    '新B': (first_part['B'] + second_part['B']) / 2
})

# 输出结果
print(result)

运行代码后会得到12行的结果,每行对应原数据首尾配对的平均值,符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 00:13:24