Working with data
Analyze and visualize data from APIs
Let's explore how to grab data from online services, clean it up, and make some nice graphs.
Building on APIs
Remember learning about APIs? They're like menus for programs to order data from other programs. We used one to get a list of books.
Now, we'll use an API to fetch some real-world data: weather forecasts. We'll then use Python to make sense of it.
Get 7 days of weather
We'll use a free weather API to get a forecast for the next week. You can pick any city you like.
import requests
CITY = "London"
API_KEY = "your_api_key_here"
url = f"http://api.weatherapi.com/v1/forecast.json?key={API_KEY}&q={CITY}&days=7"
response = requests.get(url)
data = response.json()
print(data.keys())"your_api_key_here" with your actual key.Load into pandas
The data from the API comes as a big dictionary. It's often easier to work with this kind of data in a table format. The pandas library is perfect for this.
import pandas as pd
forecast_days = data['forecast']['forecastday']
# Extract relevant data for each day
weather_data = []
for day in forecast_days:
date = day['date']
temp = day['day']['avgtemp_c']
condition = day['day']['condition']['text']
weather_data.append([date, temp, condition])
# Create a DataFrame
df = pd.DataFrame(weather_data, columns=['Date', 'AvgTemp_C', 'Condition'])
print(df.head())DataFrame is like a spreadsheet or a table in a database. It makes organizing and analyzing data much simpler.Visualize the data
Reading numbers is one thing, but seeing a picture often tells a story faster. Let's make a simple chart to visualize the temperatures.
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 6))
plt.plot(df['Date'], df['AvgTemp_C'], marker='o')
plt.title('7-Day Average Temperature Forecast')
plt.xlabel('Date')
plt.ylabel('Average Temperature (°C)')
plt.grid(True)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()This code uses matplotlib to draw a line graph showing how the average temperature changes over the next seven days.
Save to CSV
Sometimes you'll want to save your processed data to a file. CSV (Comma Separated Values) is a very common and easy-to-read format.
output_filename = 'weather_forecast.csv'
df.to_csv(output_filename, index=False)
print(f"Data saved to {output_filename}")The index=False part tells pandas not to write the row numbers into the CSV file, as we usually don't need them there.
Complete example
Here's all the code we've looked at, put together. Make sure you have requests, pandas, and matplotlib installed.
import requests
import pandas as pd
import matplotlib.pyplot as plt
# 1. Get data from API
CITY = "Paris"
API_KEY = "your_api_key_here" # Replace with your WeatherAPI.com key
url = f"http://api.weatherapi.com/v1/forecast.json?key={API_KEY}&q={CITY}&days=7"
response = requests.get(url)
data = response.json()
# 2. Load into pandas DataFrame
forecast_days = data['forecast']['forecastday']
weather_data = []
for day in forecast_days:
date = day['date']
temp = day['day']['avgtemp_c']
condition = day['day']['condition']['text']
weather_data.append([date, temp, condition])
df = pd.DataFrame(weather_data, columns=['Date', 'AvgTemp_C', 'Condition'])
# 3. Visualize the data
plt.figure(figsize=(10, 6))
plt.plot(df['Date'], df['AvgTemp_C'], marker='o')
plt.title(f'7-Day Average Temperature Forecast for {CITY}')
plt.xlabel('Date')
plt.ylabel('Average Temperature (°C)')
plt.grid(True)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
# 4. Save to CSV
output_filename = 'weather_forecast_paris.csv'
df.to_csv(output_filename, index=False)
print(f"Data saved to {output_filename}")What you've accomplished
- Fetched data from a real-world API.
- Transformed raw JSON data into a structured
pandasDataFrame. - Created a visual representation of your data using
matplotlib. - Saved your processed data to a common file format (.csv).
These are core skills for anyone working with data! You've taken your first steps into data analysis and visualization.
Next steps
Try changing the city in the code. Explore other data points from the weather API, like maxwind_kph or avghumidity.
- Can you plot the maximum temperature instead of the average?
- What if you tried to get weather for two different cities and compare them?
- Look into different types of plots with
matplotliborseaborn(another popular plotting library).