Examples

This page demonstrates practical weather data analysis using weathervault.

Temperature Analysis

Daily Temperature Range

Calculate and visualize daily temperature ranges:

import weathervault as wv
import polars as pl

# Get hourly data for a full year
weather = wv.get_weather_data("725030-14732", years=2024, make_hourly=True)

# Calculate daily min/max/mean temperatures
daily_temps = weather.group_by_dynamic("time", every="1d").agg([
    pl.col("temp").min().alias("min_temp"),
    pl.col("temp").max().alias("max_temp"),
    pl.col("temp").mean().alias("mean_temp"),
]).with_columns([
    (pl.col("max_temp") - pl.col("min_temp")).alias("temp_range")
])

# Find days with largest temperature swings
print("Days with largest temperature swings:")
daily_temps.sort("temp_range", descending=True).head(10)
Days with largest temperature swings:
shape: (10, 5)
timemin_tempmax_tempmean_temptemp_range
datetime[μs, America/New_York]f64f64f64f64
2024-03-14 00:00:00 EDT6.721.712.27515.0
2024-10-21 00:00:00 EDT13.327.220.27916713.9
2024-05-01 00:00:00 EDT10.623.915.32513.3
2024-06-23 00:00:00 EDT21.134.428.36666713.3
2024-01-13 00:00:00 EST2.215.09.25416712.8
2024-04-09 00:00:00 EDT10.623.316.54583312.7
2024-04-28 00:00:00 EDT10.623.315.86666712.7
2024-05-02 00:00:00 EDT10.623.315.45833312.7
2024-04-29 00:00:00 EDT15.627.821.49166712.2
2024-04-15 00:00:00 EDT14.426.119.511.7

Temperature Distribution by Month

# Temperature statistics by month
monthly_dist = weather.group_by(pl.col("time").dt.month()).agg([
    pl.col("temp").mean().alias("mean"),
    pl.col("temp").median().alias("median"),
    pl.col("temp").std().alias("std"),
    pl.col("temp").quantile(0.25).alias("q25"),
    pl.col("temp").quantile(0.75).alias("q75"),
]).sort("time")

monthly_dist
shape: (12, 6)
timemeanmedianstdq25q75
i8f64f64f64f64f64
12.7912633.34.446986-0.65.6
24.0415233.93.6017721.76.1
38.0940787.84.0837455.610.0
411.59833310.64.5053648.313.9
517.68655917.84.81285114.421.1
………………
824.48669424.43.57572222.226.7
920.62666720.62.89847418.322.8
1016.51155916.74.05993513.919.4
1111.54486111.15.2745678.314.4
123.8481083.35.3289350.67.8

Wind Analysis

Wind Speed Statistics

# Wind speed analysis
wind_stats = weather.filter(pl.col("ws").is_not_null()).select([
    pl.col("ws").mean().alias("mean_wind_speed"),
    pl.col("ws").max().alias("max_wind_speed"),
    pl.col("ws").quantile(0.95).alias("wind_95th_percentile"),
])

print(wind_stats)
shape: (1, 3)
┌─────────────────┬────────────────┬──────────────────────┐
│ mean_wind_speed ┆ max_wind_speed ┆ wind_95th_percentile │
│ ---             ┆ ---            ┆ ---                  │
│ f64             ┆ f64            ┆ f64                  │
╞═════════════════╪════════════════╪══════════════════════╡
│ 4.646923        ┆ 17.0           ┆ 9.3                  │
└─────────────────┴────────────────┴──────────────────────┘

Prevailing Wind Direction

# Most common wind directions
wind_dirs = weather.filter(
    pl.col("wd").is_not_null()
).group_by("wd").agg([
    pl.len().alias("count")
]).sort("count", descending=True)

print("Top 5 wind directions:")
print(wind_dirs.head(5))
Top 5 wind directions:
shape: (5, 2)
┌─────┬───────┐
│ wd  ┆ count │
│ --- ┆ ---   │
│ i32 ┆ u32   │
╞═════╪═══════╡
│ 50  ┆ 510   │
│ 310 ┆ 485   │
│ 40  ┆ 426   │
│ 320 ┆ 415   │
│ 300 ┆ 406   │
└─────┴───────┘

Calm vs Windy Days

# Classify days by wind speed
daily_wind = weather.group_by_dynamic("time", every="1d").agg([
    pl.col("ws").mean().alias("mean_wind_speed"),
    pl.col("ws").max().alias("max_wind_speed"),
])

calm_days = daily_wind.filter(pl.col("mean_wind_speed") < 2).height
windy_days = daily_wind.filter(pl.col("mean_wind_speed") > 5).height

print(f"Calm days (< 2 m/s): {calm_days}")
print(f"Windy days (> 5 m/s): {windy_days}")
Calm days (< 2 m/s): 6
Windy days (> 5 m/s): 123

Humidity and Comfort

Relative Humidity Distribution

# Humidity statistics by season
weather_with_season = weather.with_columns([
    pl.col("time").dt.month().alias("month")
]).with_columns([
    pl.when(pl.col("month").is_in([12, 1, 2])).then(pl.lit("Winter"))
    .when(pl.col("month").is_in([3, 4, 5])).then(pl.lit("Spring"))
    .when(pl.col("month").is_in([6, 7, 8])).then(pl.lit("Summer"))
    .otherwise(pl.lit("Fall"))
    .alias("season")
])

seasonal_humidity = weather_with_season.group_by("season").agg([
    pl.col("rh").mean().alias("mean_humidity"),
    pl.col("rh").min().alias("min_humidity"),
    pl.col("rh").max().alias("max_humidity"),
])

seasonal_humidity
shape: (4, 4)
seasonmean_humiditymin_humiditymax_humidity
strf64f64f64
"Summer"59.81277819.594.1
"Winter"58.11857822.696.8
"Spring"60.1006815.1100.0
"Fall"54.9668515.490.3

Heat Index Calculation

Calculate apparent temperature combining heat and humidity:

# Simplified heat index formula (Fahrenheit)
# HI = c1 + c2*T + c3*RH + c4*T*RH + c5*T^2 + c6*RH^2 + c7*T^2*RH + c8*T*RH^2 + c9*T^2*RH^2

def calculate_heat_index(temp_c, rh):
    """Calculate heat index from temperature (C) and relative humidity (%)."""
    # Convert to Fahrenheit
    T = (temp_c * 9/5) + 32
    RH = rh

    # Rothfusz regression (valid for T >= 80°F, RH >= 40%)
    HI = (
        -42.379 +
        2.04901523 * T +
        10.14333127 * RH -
        0.22475541 * T * RH -
        0.00683783 * T * T -
        0.05481717 * RH * RH +
        0.00122874 * T * T * RH +
        0.00085282 * T * RH * RH -
        0.00000199 * T * T * RH * RH
    )

    # Convert back to Celsius
    return (HI - 32) * 5/9

# Calculate heat index for summer
summer = weather_with_season.filter(
    pl.col("season") == "Summer"
).filter(
    pl.col("temp").is_not_null() & pl.col("rh").is_not_null()
)

# Find hot, humid days
hot_humid = summer.filter(
    (pl.col("temp") > 27) & (pl.col("rh") > 60)
).select([
    "time", "temp", "rh"
])

print(f"Hot and humid observations: {hot_humid.height}")
hot_humid.head(10)
Hot and humid observations: 150
shape: (10, 3)
timetemprh
datetime[μs, America/New_York]f64f64
2024-06-22 09:00:00 EDT27.862.6
2024-06-22 15:00:00 EDT28.969.7
2024-06-22 16:00:00 EDT28.960.9
2024-06-23 09:00:00 EDT28.962.8
2024-06-30 09:00:00 EDT27.874.3
2024-06-30 10:00:00 EDT27.871.6
2024-06-30 11:00:00 EDT28.372.1
2024-06-30 12:00:00 EDT27.871.6
2024-06-30 13:00:00 EDT28.969.7
2024-06-30 14:00:00 EDT28.969.7

Precipitation Indicators

While ISD data doesn’t directly provide precipitation amounts, we can infer wet conditions from high humidity and low visibility:

# Identify likely precipitation events
wet_conditions = weather.filter(
    (pl.col("rh") > 95) &
    (pl.col("visibility") < 5000)  # Less than 5km visibility
).select([
    "time", "temp", "rh", "visibility"
])

print(f"Observations with likely precipitation: {wet_conditions.height}")
wet_conditions.head(10)
Observations with likely precipitation: 7
shape: (7, 4)
timetemprhvisibility
datetime[μs, America/New_York]f64f64i32
2024-01-13 08:00:00 EST12.896.1805
2024-01-27 01:00:00 EST5.695.9800
2024-04-12 09:00:00 EDT12.896.1402
2024-04-12 10:00:00 EDT13.0100.0402
2024-05-06 06:00:00 EDT11.196.7402
2024-05-06 07:00:00 EDT11.796.11609
2024-05-06 08:00:00 EDT11.796.11600

Multi-Station Comparison

Compare weather patterns across nearby stations:

# Get data for three NYC airports
lga = wv.get_weather_data("725030-14732", years=2024, incl_stn_info=True)
jfk = wv.get_weather_data("744860-94789", years=2024, incl_stn_info=True)
ewr = wv.get_weather_data("725020-14734", years=2024, incl_stn_info=True)

# Combine
nyc = pl.concat([lga, jfk, ewr])

# Compare temperature statistics
comparison = nyc.group_by(["id", "name"]).agg([
    pl.col("temp").mean().alias("mean_temp"),
    pl.col("temp").std().alias("std_temp"),
    pl.col("temp").min().alias("min_temp"),
    pl.col("temp").max().alias("max_temp"),
    pl.len().alias("num_obs"),
])

comparison
shape: (3, 7)
idnamemean_tempstd_tempmin_tempmax_tempnum_obs
strstrf64f64f64f64u32
"725020-14734""NEWARK LIBERTY INTERNATIONAL A…14.7278749.630412-11.737.213099
"725030-14732""LA GUARDIA AIRPORT"14.1575319.100941-11.135.613420
"744860-94789""JOHN F KENNEDY INTERNATIONAL A…13.7982418.890841-10.634.413052

Temperature Differences

# Align data by hour and calculate differences
# (simplified - assumes matching timestamps)
lga_hourly = lga.filter(pl.col("temp").is_not_null()).select([
    "time", pl.col("temp").alias("lga_temp")
]).sort("time")

jfk_hourly = jfk.filter(pl.col("temp").is_not_null()).select([
    "time", pl.col("temp").alias("jfk_temp")
]).sort("time")

# Join on time
temp_diff = lga_hourly.join(jfk_hourly, on="time").with_columns([
    (pl.col("lga_temp") - pl.col("jfk_temp")).abs().alias("temp_difference")
])

print(f"Mean temperature difference: {temp_diff['temp_difference'].mean():.2f}°C")
print(f"Max temperature difference: {temp_diff['temp_difference'].max():.2f}°C")
Mean temperature difference: 1.23°C
Max temperature difference: 9.40°C

Extreme Weather Events

Heat Waves

Identify prolonged periods of high temperatures:

# Daily maximum temperatures
daily_max = weather.group_by_dynamic("time", every="1d").agg([
    pl.col("temp").max().alias("max_temp")
])

# Find consecutive hot days (> 30°C)
hot_threshold = 30
hot_days = daily_max.filter(pl.col("max_temp") > hot_threshold)

print(f"Days exceeding {hot_threshold}°C: {hot_days.height}")
hot_days.head(10)
Days exceeding 30°C: 30
shape: (10, 2)
timemax_temp
datetime[μs, America/New_York]f64
2024-06-19 00:00:00 EDT31.7
2024-06-20 00:00:00 EDT33.3
2024-06-21 00:00:00 EDT35.6
2024-06-22 00:00:00 EDT33.9
2024-06-23 00:00:00 EDT34.4
2024-06-25 00:00:00 EDT32.2
2024-06-26 00:00:00 EDT32.8
2024-06-30 00:00:00 EDT30.6
2024-07-05 00:00:00 EDT31.1
2024-07-06 00:00:00 EDT32.2

Cold Snaps

# Daily minimum temperatures
daily_min = weather.group_by_dynamic("time", every="1d").agg([
    pl.col("temp").min().alias("min_temp")
])

# Find freezing days
freezing_days = daily_min.filter(pl.col("min_temp") < 0)

print(f"Days with freezing temperatures: {freezing_days.height}")
freezing_days.head(10)
Days with freezing temperatures: 37
shape: (10, 2)
timemin_temp
datetime[μs, America/New_York]f64
2024-01-02 00:00:00 EST-1.1
2024-01-04 00:00:00 EST-1.7
2024-01-05 00:00:00 EST-2.2
2024-01-14 00:00:00 EST-2.2
2024-01-15 00:00:00 EST-4.4
2024-01-16 00:00:00 EST-4.4
2024-01-17 00:00:00 EST-7.2
2024-01-18 00:00:00 EST-5.0
2024-01-19 00:00:00 EST-2.8
2024-01-20 00:00:00 EST-7.2

Data Quality Assessment

Observation Frequency

# Calculate time gaps between observations
weather_sorted = weather.sort("time")

time_diffs = weather_sorted.select([
    pl.col("time"),
    pl.col("time").diff().dt.total_minutes().alias("minutes_since_last")
])

# Distribution of observation intervals
print(time_diffs["minutes_since_last"].describe())
shape: (9, 2)
┌────────────┬────────┐
│ statistic  ┆ value  │
│ ---        ┆ ---    │
│ str        ┆ f64    │
╞════════════╪════════╡
│ count      ┆ 8783.0 │
│ null_count ┆ 1.0    │
│ mean       ┆ 60.0   │
│ std        ┆ 0.0    │
│ min        ┆ 60.0   │
│ 25%        ┆ 60.0   │
│ 50%        ┆ 60.0   │
│ 75%        ┆ 60.0   │
│ max        ┆ 60.0   │
└────────────┴────────┘

Data Completeness by Variable

# Calculate completeness percentage for each variable
completeness = pl.DataFrame({
    "variable": ["temp", "dew_point", "rh", "wd", "ws", "atmos_pres", "ceil_hgt", "visibility"],
    "completeness_%": [
        (weather["temp"].is_not_null().sum() / weather.height * 100),
        (weather["dew_point"].is_not_null().sum() / weather.height * 100),
        (weather["rh"].is_not_null().sum() / weather.height * 100),
        (weather["wd"].is_not_null().sum() / weather.height * 100),
        (weather["ws"].is_not_null().sum() / weather.height * 100),
        (weather["atmos_pres"].is_not_null().sum() / weather.height * 100),
        (weather["ceil_hgt"].is_not_null().sum() / weather.height * 100),
        (weather["visibility"].is_not_null().sum() / weather.height * 100),
    ]
}).sort("completeness_%", descending=True)

completeness
shape: (8, 2)
variablecompleteness_%
strf64
"dew_point"99.943078
"visibility"99.943078
"temp"99.931694
"rh"99.931694
"ws"99.908925
"wd"94.159836
"atmos_pres"91.939891
"ceil_hgt"78.836521

Exporting for Visualization

Prepare data for plotting with other libraries:

# Create a clean dataset for visualization
viz_data = weather.select([
    "time",
    "temp",
    "dew_point",
    "rh",
    "ws",
]).filter(
    pl.col("temp").is_not_null()
)

# Save to CSV for use with matplotlib, seaborn, plotly, etc.
viz_data.write_csv("weather_viz_data.csv")

Next Steps