python实现excel数据自动统计

  • 读取数据 :首先,使用pandas读取Excel文件中的数据。

  • 分组 :使用groupby根据指定的分组列对数据进行分组。

  • 统计次数:自动统计每组的指定列中每个唯一值出现的次数,和统计满足特定条件的计数

  • **保存:**将需要的统计结果保存在新的文件中

python 复制代码
import pandas as pd

# 定义一个函数来计算特定值组合的计数  
def count_specific_values(group, target_rs, target_lcd_s):  
    # 筛选特定值组合的行  
    filtered = group[(group['rs'] == target_rs) & (group['lcd_s'] == target_lcd_s)]  
    # 返回计数  
    return len(filtered)


file_path_1 = r'1.xlsx'  
sheet_name_1 = 'a' 
file_path_2 = r'2.xlsx'  
sheet_name_2 = 'b' 

df_succes = pd.read_excel(file_path_1,sheet_name=sheet_name_1)
df2_fail = pd.read_excel(file_path_2,sheet_name=sheet_name_2)

# 合并数据
df_data_total = pd.concat([df_succes, df2_fail], axis=0)

# 按name号分组
grouped_data = df_data_total.groupby("name")

# 使用pivot_table计算每个name组中的数据
auth_pivot_table = grouped_data["rs"].value_counts().unstack(fill_value=0) #rs的值分为0 2 4

# 计算0的次数
auth_pivot_table['0_cnt'] = auth_pivot_table[0]

# 计算2的次数
auth_pivot_table['2_cnt'] = auth_pivot_table[2]

# 计算4的次数
auth_pivot_table['4_cnt'] = auth_pivot_table[4]

# 计算AA次数
auth_pivot_table['AA'] = grouped_data.apply(lambda x: count_specific_values(x, 0, 2))

# 重置索引
auth_pivot_table.reset_index(inplace=True)

#选取特定列输出
result = auth_pivot_table[['name', '0_cnt', '2_cnt', '4_cnt', 'AA']]

# 重命名列名
result.columns = ['name', '0_cnt', '2_cnt', '4_cnt', 'AA']

# 保存结果到Excel文件
result.to_excel("name.xlsx")
print('save succ.')
相关推荐
IVEN_16 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang17 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮17 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling17 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮21 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽21 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞2 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽2 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers