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.')
相关推荐
another heaven2 小时前
【Qt VS2022调试时无法查看QString等Qt变量信息】解决方法
开发语言·qt
A黄俊辉A2 小时前
axios+ts封装
开发语言·前端·javascript
Y学院2 小时前
Python 数据分析:从新手到高手的“摸鱼”指南
python·数据分析
杨福瑞3 小时前
C语⾔内存函数
c语言·开发语言
深耕AI3 小时前
【PyTorch训练】准确率计算(代码片段拆解)
人工智能·pytorch·python
eqwaak03 小时前
科技信息差(9.12)
开发语言·python·科技·量子计算
axban3 小时前
QT M/V架构开发实战:QStringListModel介绍
开发语言·数据库·qt
刘媚-海外3 小时前
Go语言开发AI应用
开发语言·人工智能·golang·go
Blossom.1183 小时前
从“能写”到“能干活”:大模型工具调用(Function-Calling)的工程化落地指南
数据库·人工智能·python·深度学习·机器学习·计算机视觉·oracle