import pandas as pd import datetime now = datetime.datetime.now().strftime('%Y%m%d') # 获取当前日期,格式为年月日 data = pd.read_excel(r'E:\每日数据\MISPOS明细.xlsx',dtype={'商户编号':str,'终端编号':str, '处理情况': str}) rows = data.shape[0] # 获取行数 shape[1]获取列数 department_list = [] for i in range(rows): temp = data["省份"][i] if temp not in department_list: department_list.append(temp) # 将省份的分类存在一个列表中 for department in department_list: new_df = pd.DataFrame() for i in range(0, rows): if data["省份"][i] == department: new_df = pd.concat([new_df, data.iloc[[i], :]], axis=0, ignore_index=True) # 上面的循环效率太低了,这么做太蠢了,其实可以用pandas的条件筛选 new_df = data[data["省份"] == department] # 如果多条件筛选,new_df = data[(data["省份"] == department)&()&()] 括号里写条件用 & 连起来 new_df.to_excel(str(department) +"旧机具未处理明细" + ".xlsx", sheet_name=department, index=False)
时间: 2024-01-28 12:05:46 浏览: 24
这段代码的主要功能是读取一个Excel文件,然后根据其中的“省份”列进行分组,将同一省份的行数据写入到一个新的Excel文件中。具体流程如下:
1. 使用Pandas库中的read_excel函数读取一个Excel文件,存储到data变量中。
2. 使用shape属性获取data的行数和列数。
3. 创建一个空列表department_list,用于存储不重复的“省份”值。
4. 遍历所有行,将不重复的“省份”值存储到department_list中。
5. 遍历department_list中的所有“省份”值,创建一个新的DataFrame对象new_df。
6. 遍历data中的所有行,如果行的“省份”值等于当前遍历到的“省份”值,则将该行数据添加到new_df中。
7. 将new_df写入到一个以“省份”命名的Excel文件中。
8. 如果需要多条件筛选,可以在第6步中使用Pandas的条件筛选功能,将筛选结果存储到new_df中。
9. 最终生成的Excel文件名格式为“省份+旧机具未处理明细.xlsx”,其中“省份”为具体的省份名称。
相关问题
pd.to_datetime(date).strftime("%Y%m%d")
这是一个Python pandas库中的函数,它将日期或日期字符串转换为指定格式的字符串。具体地,它将一个日期对象或日期字符串转换为年月日(%Y%m%d)的字符串格式。其中,%Y代表四位数的年份,%m代表两位数的月份,%d代表两位数的日期。例如,如果date为"2022-01-01",则该函数将返回"20220101"。
帮我重写如下python代码,#coding=utf-8-sig import re import os import xlrd import xlwt import time import datetime import math #import pandas import sys import shutil #通用部分 def time_mc(number_t): localTime = time.strftime("%Y%m%d%H%M%S", time.localtime()) time_mc_n
当然可以,以下是重写后的代码:
```python
#coding=utf-8-sig
import re
import os
import xlrd
import xlwt
import time
import datetime
import math
import sys
import shutil
# 通用部分
def time_mc(number_t):
localTime = time.strftime("%Y%m%d%H%M%S", time.localtime())
time_mc_n = localTime + str(number_t)
return time_mc_n
def create_dir(path):
if not os.path.exists(path):
os.makedirs(path)
def del_file(path):
if os.path.exists(path):
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.remove(path)
def get_file_path(root_path, file_type):
file_list = []
for dirpath, dirnames, filenames in os.walk(root_path):
for filename in filenames:
if filename.endswith(file_type):
file_list.append(os.path.join(dirpath, filename))
return file_list
# 主程序
if __name__ == '__main__':
pass
```
我将原来的代码中的注释进行了调整,并且将一些通用函数进行了函数封装,以方便代码的复用性和可读性。