使用python完成excel文件的合并,并完成简单的数据统计

Python脚本实现了以下功能:

  1. 合并多个Excel文件 :脚本遍历当前目录下的所有.xlsx文件,读取每个文件的内容并合并到一个大的DataFrame中,然后将合并后的数据写入到名为combined_data.xlsx的新文件中。

  2. 统计指定列的重复值 :读取刚刚合并的combined_data.xlsx文件,检查其中的某一列(在这个例子中为攻击类型)是否存在且数据类型为字符串。如果条件满足,则统计该列中不同文本的出现次数,并将重复值及其出现次数按照降序排列。最后,将统计结果写入同一个Excel文件的第二个工作表(Sheet2)中。

注意事项: 以下代码使用了 openpyxlpandas这两个第三方库 ,使用以下命令获取。

复制代码
pip install openpyxl
pip install pandas
python 复制代码
import os
import openpyxl
import pandas as pd

# 获取当前脚本所在目录
script_dir = os.path.dirname(__file__)
output_file = os.path.join(script_dir, 'combined_data.xlsx')

# 合并当前目录下所有xlsx文件
current_directory = os.getcwd()
file_list = [os.path.join(current_directory, f) for f in os.listdir(current_directory) if f.endswith('.xlsx')]

# 初始化一个空列表来存储所有数据帧
data_frames = []

# 逐个读取xlsx文件并合并
for file in file_list:
    df = pd.read_excel(file)
    data_frames.append(df)

# 合并所有数据帧
combined_df = pd.concat(data_frames, ignore_index=True)

# 将合并后的数据写入新创建的xlsx文件中
combined_df.to_excel(output_file, index=False)

# 检查并处理列名为'攻击类型'的列
target_column = '攻击类型'
if target_column in combined_df.columns and combined_df[target_column].dtype == 'object':
    # 统计该列总行数
    total_rows = combined_df.shape[0]

    # 去除重复值并计算重复次数
    duplicates = combined_df[target_column].duplicated(keep=False)
    duplicate_counts = combined_df[duplicates][target_column].value_counts().reset_index()
    duplicate_counts.columns = [target_column, 'occurrences']

    # 按照重复次数降序排列
    duplicate_counts = duplicate_counts.sort_values(by='occurrences', ascending=False)

    # 新增Sheet2
    with pd.ExcelWriter(output_file, engine='openpyxl', mode='a') as writer:
        writer.book = openpyxl.load_workbook(output_file)
        duplicate_counts.to_excel(writer, sheet_name='Sheet2', index=False)
    print(f"{target_column}重复数据已写入到{output_file}的Sheet2中。")
else:
    print(f"{target_column}不存在或不是字符串类型,请检查数据")

print(f"总行数: {total_rows}")
相关推荐
东方珵蕴3 分钟前
COBOL语言的折线图
开发语言·后端·golang
知识中的海王3 分钟前
js逆向入门图灵爬虫练习平台 第四题学习
开发语言·前端·javascript
光算科技3 分钟前
无限滚动(Infinite Scroll)页面谷歌不收录!必须改回分页吗?
java·开发语言
重生之我要成为代码大佬5 分钟前
从零讲透DFS-深度优先搜索-2(排序与组合)
开发语言·python·算法·深度优先遍历
那年那棵树6 分钟前
【爬虫】网易云音乐评论数据爬取
javascript·爬虫·python
日升_rs7 分钟前
Browser-use:基于 Python 的智能浏览器自动化 AI 工具调研与实战
python·ai·浏览器
zidea8 分钟前
我和我的 AI Agent(3)记忆模块设计上花了不少心思,看看记忆细胞和记忆片段是如何设计以及实现的
人工智能·python·deepseek
那年那棵树9 分钟前
【爬虫】携程旅游项目数据爬取
爬虫·python·旅游
老大白菜9 分钟前
FastAPI-Cache2: 高效Python缓存库
python·缓存·fastapi
JavaEdge在掘金10 分钟前
Llama 4 家族:原生多模态 AI 创新的新时代开启
python