如何修改现有的代码,以便将其输出为一个包含1960-2020年每年6月至8月的月平均气温数据的Excel表格?
时间: 2024-10-23 20:13:24 浏览: 36
为了将每个月的平均气温数据输出到新的Excel表格中,你可以按如下步骤修改现有代码:
1. **创建一个空DataFrame存储结果**:
初始化一个新的DataFrame,用于存放每个月的平均气温数据以及对应的年份。
```python
result = pd.DataFrame(columns=['Year', 'Month', 'Average_Temperature'])
```
2. **遍历每个年份和月份,计算平均气温并添加到新DataFrame**:
使用pandas的`GroupBy`功能按年份和月份分组,然后计算平均气温。
```python
for year in range(1960, 2021):
temp_for_year = df[df['Year'] == year]
monthly_avg_temp = temp_for_year.groupby(['Month']).mean()['Temperature']
for month, avg_temp in monthly_avg_temp.items():
result = result.append({'Year': year, 'Month': month + 1, 'Average_Temperature': avg_temp}, ignore_index=True)
```
这里假设月份数字从1开始(例如6月对应1,7月对应2,依此类推),`ignore_index=True`是为了让索引在每次追加时自动生成。
3. **将结果写入新的Excel文件**:
使用`to_excel()`函数将结果DataFrame保存到新的Excel文件。
```python
result.to_excel('annual_monthly_average_temperature.xlsx', index=False)
```
现在,你已经有了一个名为`annual_monthly_average_temperature.xlsx`的新Excel文件,其中包含了每年6月至8月的月平均气温数据。
阅读全文
相关推荐















