如何在Python中读取实际的历史天气数据用于绘制?
时间: 2024-11-03 12:18:50 浏览: 29
在Python中,通常我们会使用第三方API或数据集来获取历史天气数据,如requests库配合openweathermap API、pandas-datareader库访问Yahoo Finance等。以下是使用requests库从OpenWeatherMap API获取伦敦过去一周平均气温的一个例子(假设你已经注册并获得了API密钥):
首先,确保安装了`requests`库,如果未安装,可以使用`pip install requests`命令安装。
```python
import requests
# 替换为你的API密钥
api_key = "your_openweathermap_api_key"
city_id = "2172797" # 伦敦的ID,可以在OpenWeatherMap官网查询
url = f"http://api.openweathermap.org/data/2.5/onecall?lat=51.5074&lon=-0.1278&appid={api_key}&exclude=current,minutely,hourly,daily&units=metric"
response = requests.get(url)
data = response.json()
# 通常天气数据会在"data"字典的"main"键下,找到"temp"(温度)和"temp_min"(最低温度)、"temp_max"(最高温度)
past_temps = data["main"]["temp"]
avg_temp = sum(past_temps[-7:]) / len(past_temps[-7:]) # 取最近一周平均温度
print(f"过去一周伦敦的平均温度大约是{avg_temp}摄氏度")
```
请注意,实际操作时可能需要处理API请求限制、错误处理以及更复杂的数据解析。如果你想要直接绘图,还需要将获取到的数据按照日期排列并存储在一个适当的数据结构中,然后按照之前介绍的方式绘制图表。
阅读全文