公司网站 个人备案,电商哪个平台好,给公司做企业网站,怎么做网站推广临沂Python脚本实现了以下功能#xff1a; 合并多个Excel文件#xff1a;脚本遍历当前目录下的所有.xlsx文件#xff0c;读取每个文件的内容并合并到一个大的DataFrame中#xff0c;然后将合并后的数据写入到名为combined_data.xlsx的新文件中。 统计指定列的重复值#xff1…Python脚本实现了以下功能 合并多个Excel文件脚本遍历当前目录下的所有.xlsx文件读取每个文件的内容并合并到一个大的DataFrame中然后将合并后的数据写入到名为combined_data.xlsx的新文件中。 统计指定列的重复值读取刚刚合并的combined_data.xlsx文件检查其中的某一列在这个例子中为攻击类型是否存在且数据类型为字符串。如果条件满足则统计该列中不同文本的出现次数并将重复值及其出现次数按照降序排列。最后将统计结果写入同一个Excel文件的第二个工作表Sheet2中。
注意事项 以下代码使用了 openpyxl和pandas这两个第三方库 使用以下命令获取。
pip install openpyxl
pip install pandas
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_indexTrue)# 将合并后的数据写入新创建的xlsx文件中
combined_df.to_excel(output_file, indexFalse)# 检查并处理列名为攻击类型的列
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(keepFalse)duplicate_counts combined_df[duplicates][target_column].value_counts().reset_index()duplicate_counts.columns [target_column, occurrences]# 按照重复次数降序排列duplicate_counts duplicate_counts.sort_values(byoccurrences, ascendingFalse)# 新增Sheet2with pd.ExcelWriter(output_file, engineopenpyxl, modea) as writer:writer.book openpyxl.load_workbook(output_file)duplicate_counts.to_excel(writer, sheet_nameSheet2, indexFalse)print(f{target_column}重复数据已写入到{output_file}的Sheet2中。)
else:print(f{target_column}不存在或不是字符串类型请检查数据)print(f总行数: {total_rows})