1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
| import pandas as pd
import numpy as np
def process_df(df, time_range=pd.date_range('2021-12-01', '2024-11-20', freq='D')):
# 去掉前两行
df = df.iloc[2:]
# 将第三行设置为header
df.columns = df.iloc[0]
# 去掉第四行
df = df.iloc[2:]
# 将日期列设置为index
df['日期'] = pd.to_datetime(df['日期'])
df.set_index('日期', inplace=True)
# 如果第一行第一个值不是数字则设为空
if str(df.iloc[0, 0]).isdigit() == False:
df.iloc[0, 0] = np.nan
# 将0值改为空值
df = df.replace(0, np.nan)
# 向前填充再向后填充
df = df.fillna(method='ffill').fillna(method='bfill')
print(df.head())
return df
def process_excel(input_path, output_path, sheet_names=None):
# 读取 Excel 文件中的所有 sheet 名称
if sheet_names is None:
sheet_names = pd.ExcelFile(input_path).sheet_names
# 处理数据
processed_df_dict = {}
for sheet_name in sheet_names:
print('正在处理', sheet_name)
df = pd.read_excel(input_path, header=None, sheet_name=sheet_name)
# 移除重复的索引
df = df.loc[~df.index.duplicated(keep='first')]
# 处理数据
processed_df = process_df(df)
processed_df_dict[sheet_name] = processed_df
# 保存到新的 Excel 文件
with pd.ExcelWriter(output_path) as writer:
for sheet_name, df in processed_df_dict.items():
df.to_excel(writer, sheet_name=sheet_name)
print(f'已保存到 {output_path}')
# 使用示例
if __name__ == "__main__":
input_path = 'input.xlsx'
output_path = 'output.xlsx'
process_excel(input_path, output_path)
|