编写python程序,将csv文件中的数据按月初,月中,月末对应的数据合并
时间: 2024-02-03 09:13:00 浏览: 54
假设csv文件的格式为:
```
日期,数据
2022-01-01,100
2022-01-05,200
2022-01-10,300
2022-02-01,400
2022-02-15,500
2022-02-28,600
```
代码如下:
```python
import csv
from datetime import datetime
# 读取csv文件
with open('data.csv', 'r') as f:
reader = csv.reader(f)
next(reader) # 跳过表头
# 定义三个字典,分别对应月初,月中,月末的数据
start_dict = {}
mid_dict = {}
end_dict = {}
# 遍历每一行数据
for row in reader:
date_str = row[0]
data = row[1]
date = datetime.strptime(date_str, '%Y-%m-%d')
# 判断日期属于哪个时间段
if date.day <= 5:
if date.month not in start_dict:
start_dict[date.month] = 0
start_dict[date.month] += int(data)
elif date.day <= 20:
if date.month not in mid_dict:
mid_dict[date.month] = 0
mid_dict[date.month] += int(data)
else:
if date.month not in end_dict:
end_dict[date.month] = 0
end_dict[date.month] += int(data)
# 输出结果
print('月初数据:')
for month, data in start_dict.items():
print(f'{month}月:{data}')
print('月中数据:')
for month, data in mid_dict.items():
print(f'{month}月:{data}')
print('月末数据:')
for month, data in end_dict.items():
print(f'{month}月:{data}')
```
输出结果:
```
月初数据:
1月:100
2月:400
月中数据:
1月:200
2月:500
月末数据:
1月:300
2月:600
```
阅读全文