将每个月新增的项目建设单位找出来,将整行的数据保存到当前excel表格的新建sheet中。
import pandas as pd
import os
# 读取Excel文件
file_path = 'C:\\Users\\ceprei\\Desktop\\zsy\\python\\excel_filter\\test3.xlsx' # 文件路径
df = pd.read_excel("test3.xlsx", sheet_name="项目分项估算表")
# 按'月份'列进行升序排序
df.sort_values(by='月份', inplace=True, ascending=True)
# 按“公司”列进行去重
df.drop_duplicates(subset='建设单位', keep='first', inplace=True)
# 保存排序后的数据到新的Sheet文件
df.to_excel('newscore.xlsx')
with pd.ExcelWriter(file_path, engine='openpyxl', mode='a',if_sheet_exists='replace') as writer:
df.to_excel(writer, sheet_name='df_data', index=False)
# 自动打开Excel文件
if os.name == 'nt': # 检查是否为Windows系统
os.startfile(file_path) # 使用默认程序打开文件
print("结果已写入原有的Excel文件中的新工作表。")
测试:

结果:

- 文件打开时运行代码会报错:PermissionError: [Errno 13] Permission denied:。关闭文件运行就可以了
- 筛选行默认在第一行,否则可能会识别不到关键字
1万+

被折叠的 条评论
为什么被折叠?



