Python+pandas實(shí)現(xiàn)Excel連續(xù)數(shù)據(jù)分組求平均值
一、問題
假設(shè)我們有以下 Excel 數(shù)據(jù):
| 數(shù)據(jù) |
|---|
| 10 |
| 20 |
| 30 |
| (空) |
| 5 |
| 15 |
| (空) |
| 100 |
| 200 |
| 300 |
| 400 |
| (空) |
| 50 |
我們的目標(biāo):

- 根據(jù)空行劃分分組;
- 計(jì)算每組的 平均值;
- 將結(jié)果插入 Excel 對(duì)應(yīng)的分組末尾行。
期望結(jié)果:
| 分組 | 平均值 |
|---|---|
| 第1組 | 20 |
| 第2組 | 10 |
| 第3組 | 250 |
| 第4組 | 50 |
二、核心思路
- 使用
pandas讀取 Excel 文件; - 遍歷數(shù)據(jù)列,用空值 (
NaN) 或表格末尾作為分組邊界; - 對(duì)每組數(shù)字計(jì)算平均值;
- 將結(jié)果插入新列“平均值”,顯示在每個(gè)分組的結(jié)尾行;
- 輸出新的 Excel 文件。
三、完整 Python 代碼
import pandas as pd
# === 1. 讀取 Excel 文件 ===
df = pd.read_excel("data.xlsx")
data = df["數(shù)據(jù)"].tolist()
# === 2. 連續(xù)數(shù)字分組求平均值 ===
groups = []
current_group = []
for x in data:
if pd.isna(x): # 遇到空行,計(jì)算當(dāng)前組平均值
if current_group:
avg = sum(current_group) / len(current_group)
groups.append(avg)
current_group = []
else:
current_group.append(x)
# 處理最后一組(末尾沒有空行的情況)
if current_group:
avg = sum(current_group) / len(current_group)
groups.append(avg)
# === 3. 將結(jié)果插入新列 ===
result_list = []
i = 0
current_group = []
for x in data:
if pd.isna(x) or x == data[-1]: # 空行或最后一行
if i < len(groups): # 防止越界
result_list.append(groups[i])
i += 1
else:
result_list.append(None)
else:
result_list.append(None)
# 處理最后一行是數(shù)字的情況
if len(result_list) < len(data):
result_list.append(groups[-1])
df["平均值"] = result_list[:len(df)]
# === 4. 寫入 Excel 文件 ===
output_file = "data_avg_result.xlsx"
df.to_excel(output_file, index=False)
print("? 已生成新文件:", output_file)
四、運(yùn)行效果
運(yùn)行后生成文件 data_avg_result.xlsx:
| 數(shù)據(jù) | 平均值 |
|---|---|
| 10 | |
| 20 | |
| 30 | 20 |
| (空) | 10 |
| 5 | |
| 15 | 10 |
| (空) | 250 |
| 100 | |
| 200 | |
| 300 | |
| 400 | 250 |
| (空) | 50 |
| 50 | 50 |
每個(gè)分組的平均值自動(dòng)填充在分組末尾行,非常直觀。
五、擴(kuò)展思路
- 通用統(tǒng)計(jì)函數(shù):可輕松改造成求和、最大值、最小值、計(jì)數(shù)等統(tǒng)計(jì)功能;
- 批量處理 Excel:利用
os模塊批量處理文件夾內(nèi)的多個(gè) Excel 表格; - 數(shù)據(jù)可視化:將分組平均值繪制柱狀圖或折線圖,直觀展示趨勢;
- 高亮結(jié)果行:結(jié)合
openpyxl或xlsxwriter給平均值單元格設(shè)置顏色。
六、知識(shí)擴(kuò)展
用 Python 實(shí)現(xiàn)連續(xù)數(shù)據(jù)分組求和并回寫
1.思路分析
核心思路如下:
- 使用
pandas讀取 Excel 文件; - 遍歷數(shù)據(jù)列,用空值(
NaN)作為分組邊界; - 每組內(nèi)求和;
- 在分組結(jié)束行插入結(jié)果;
- 輸出到新 Excel 文件。
2.完整代碼實(shí)現(xiàn)
import pandas as pd
# === 1. 讀取 Excel 文件 ===
# 請(qǐng)把 "data.xlsx" 改成你的文件名(路徑也可以)
df = pd.read_excel("data.xlsx")
# 假設(shè)數(shù)據(jù)列名為 “數(shù)據(jù)”,若你的列名不同,請(qǐng)改成對(duì)應(yīng)名字
data = df["數(shù)據(jù)"].tolist()
# === 2. 連續(xù)數(shù)字分組求和 ===
groups = []
group_sum = 0
for x in data:
if pd.isna(x): # 遇到空單元格 → 分組結(jié)束
groups.append(group_sum)
group_sum = 0
else:
group_sum += x
# 最后一組
if group_sum != 0 or (len(data) and pd.isna(data[-1])):
groups.append(group_sum)
# === 3. 將結(jié)果保存為新列 ===
# 為保持對(duì)應(yīng)關(guān)系,插入空行方便對(duì)齊
result_list = []
i = 0
group_sum = 0
for x in data:
if pd.isna(x):
result_list.append(groups[i])
i += 1
else:
result_list.append(None)
# 若最后沒有空行,也在末尾加上最后一個(gè)結(jié)果
if len(result_list) < len(data):
result_list.append(groups[-1])
df["結(jié)果"] = result_list[:len(df)]
# === 4. 寫入新 Excel 文件 ===
output_file = "data_with_result.xlsx"
df.to_excel(output_file, index=False)
print("? 已生成新文件:", output_file)
4.運(yùn)行效果
執(zhí)行完代碼后,會(huì)在當(dāng)前目錄生成一個(gè)名為:
data_with_result.xlsx
七、小結(jié)
本文介紹了一種常見且高效的 Excel 自動(dòng)化方法:使用 pandas 結(jié)合空行劃分分組,自動(dòng)計(jì)算每組的平均值。
核心思路一句話總結(jié):“以空行為分組邊界,按組計(jì)算平均值,并寫回 Excel。”
這種技巧在實(shí)驗(yàn)數(shù)據(jù)統(tǒng)計(jì)、財(cái)務(wù)報(bào)表、能源數(shù)據(jù)分析等場景中非常實(shí)用。
以上就是Python+pandas實(shí)現(xiàn)Excel連續(xù)數(shù)據(jù)分組求平均值的詳細(xì)內(nèi)容,更多關(guān)于Python計(jì)算平均值的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
基于Python實(shí)現(xiàn)PDF區(qū)域文本提取工具
這篇文章主要為大家介紹了如何通過Python實(shí)現(xiàn)一個(gè)非常精簡的圖像化的PDF區(qū)域選擇提取工具,文中示例代碼講解詳細(xì),感興趣的小伙伴可以學(xué)習(xí)一下2021-12-12
淺談python3.x pool.map()方法的實(shí)質(zhì)
這篇文章主要介紹了python3.x pool.map方法的實(shí)質(zhì),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-01-01
Python prettytable模塊應(yīng)用詳解
PrettyTable 是python中的一個(gè)第三方庫,可用來生成美觀的ASCII格式的表格,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-09-09
python 移動(dòng)圖片到另外一個(gè)文件夾的實(shí)例
今天小編就為大家分享一篇python 移動(dòng)圖片到另外一個(gè)文件夾的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-01-01
pandas計(jì)數(shù) value_counts()的使用
這篇文章主要介紹了pandas計(jì)數(shù) value_counts()的使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06
python+selenium+autoit實(shí)現(xiàn)文件上傳功能
這篇文章主要介紹了python+selenium+autoit實(shí)現(xiàn)文件上傳功能,需要的朋友可以參考下2017-08-08

