# Examples

This page demonstrates practical weather data analysis using weathervault.


# Temperature Analysis


## Daily Temperature Range

Calculate and visualize daily temperature ranges:


``` python
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)

| time                             | min_temp | max_temp | mean_temp | temp_range |
|----------------------------------|----------|----------|-----------|------------|
| datetime\[μs, America/New_York\] | f64      | f64      | f64       | f64        |
| 2024-03-14 00:00:00 EDT          | 6.7      | 21.7     | 12.275    | 15.0       |
| 2024-10-21 00:00:00 EDT          | 13.3     | 27.2     | 20.279167 | 13.9       |
| 2024-05-01 00:00:00 EDT          | 10.6     | 23.9     | 15.325    | 13.3       |
| 2024-06-23 00:00:00 EDT          | 21.1     | 34.4     | 28.366667 | 13.3       |
| 2024-01-13 00:00:00 EST          | 2.2      | 15.0     | 9.254167  | 12.8       |
| 2024-04-09 00:00:00 EDT          | 10.6     | 23.3     | 16.545833 | 12.7       |
| 2024-04-28 00:00:00 EDT          | 10.6     | 23.3     | 15.866667 | 12.7       |
| 2024-05-02 00:00:00 EDT          | 10.6     | 23.3     | 15.458333 | 12.7       |
| 2024-04-29 00:00:00 EDT          | 15.6     | 27.8     | 21.491667 | 12.2       |
| 2024-04-15 00:00:00 EDT          | 14.4     | 26.1     | 19.5      | 11.7       |


## Monthly Temperature Trends


``` python
# Monthly average temperatures
monthly = weather.group_by_dynamic("time", every="1mo").agg([
    pl.col("temp").mean().alias("mean_temp"),
    pl.col("temp").min().alias("min_temp"),
    pl.col("temp").max().alias("max_temp"),
])

monthly
```


shape: (12, 4)

| time                             | mean_temp | min_temp | max_temp |
|----------------------------------|-----------|----------|----------|
| datetime\[μs, America/New_York\] | f64       | f64      | f64      |
| 2024-01-01 00:00:00 EST          | 2.791263  | -7.2     | 15.0     |
| 2024-02-01 00:00:00 EST          | 4.041523  | -4.4     | 15.6     |
| 2024-03-01 00:00:00 EST          | 8.094078  | -1.1     | 21.7     |
| 2024-04-01 00:00:00 EDT          | 11.598333 | 3.3      | 27.8     |
| 2024-05-01 00:00:00 EDT          | 17.686559 | 9.4      | 29.4     |
| …                                | …         | …        | …        |
| 2024-08-01 00:00:00 EDT          | 24.486694 | 15.0     | 34.4     |
| 2024-09-01 00:00:00 EDT          | 20.626667 | 13.9     | 28.9     |
| 2024-10-01 00:00:00 EDT          | 16.511559 | 7.2      | 27.2     |
| 2024-11-01 00:00:00 EDT          | 11.544861 | 0.0      | 26.7     |
| 2024-12-01 00:00:00 EST          | 3.848108  | -11.1    | 15.6     |


## Temperature Distribution by Month


``` python
# 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)

| time | mean      | median | std      | q25  | q75  |
|------|-----------|--------|----------|------|------|
| i8   | f64       | f64    | f64      | f64  | f64  |
| 1    | 2.791263  | 3.3    | 4.446986 | -0.6 | 5.6  |
| 2    | 4.041523  | 3.9    | 3.601772 | 1.7  | 6.1  |
| 3    | 8.094078  | 7.8    | 4.083745 | 5.6  | 10.0 |
| 4    | 11.598333 | 10.6   | 4.505364 | 8.3  | 13.9 |
| 5    | 17.686559 | 17.8   | 4.812851 | 14.4 | 21.1 |
| …    | …         | …      | …        | …    | …    |
| 8    | 24.486694 | 24.4   | 3.575722 | 22.2 | 26.7 |
| 9    | 20.626667 | 20.6   | 2.898474 | 18.3 | 22.8 |
| 10   | 16.511559 | 16.7   | 4.059935 | 13.9 | 19.4 |
| 11   | 11.544861 | 11.1   | 5.274567 | 8.3  | 14.4 |
| 12   | 3.848108  | 3.3    | 5.328935 | 0.6  | 7.8  |


# Wind Analysis


## Wind Speed Statistics


``` python
# 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


``` python
# 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


``` python
# 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


``` python
# 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)

| season   | mean_humidity | min_humidity | max_humidity |
|----------|---------------|--------------|--------------|
| str      | f64           | f64          | f64          |
| "Summer" | 59.812778     | 19.5         | 94.1         |
| "Winter" | 58.118578     | 22.6         | 96.8         |
| "Spring" | 60.10068      | 15.1         | 100.0        |
| "Fall"   | 54.96685      | 15.4         | 90.3         |


## Heat Index Calculation

Calculate apparent temperature combining heat and humidity:


``` python
# 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)

| time                             | temp | rh   |
|----------------------------------|------|------|
| datetime\[μs, America/New_York\] | f64  | f64  |
| 2024-06-22 09:00:00 EDT          | 27.8 | 62.6 |
| 2024-06-22 15:00:00 EDT          | 28.9 | 69.7 |
| 2024-06-22 16:00:00 EDT          | 28.9 | 60.9 |
| 2024-06-23 09:00:00 EDT          | 28.9 | 62.8 |
| 2024-06-30 09:00:00 EDT          | 27.8 | 74.3 |
| 2024-06-30 10:00:00 EDT          | 27.8 | 71.6 |
| 2024-06-30 11:00:00 EDT          | 28.3 | 72.1 |
| 2024-06-30 12:00:00 EDT          | 27.8 | 71.6 |
| 2024-06-30 13:00:00 EDT          | 28.9 | 69.7 |
| 2024-06-30 14:00:00 EDT          | 28.9 | 69.7 |


# Precipitation Indicators

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


``` python
# 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)

| time                             | temp | rh    | visibility |
|----------------------------------|------|-------|------------|
| datetime\[μs, America/New_York\] | f64  | f64   | i32        |
| 2024-01-13 08:00:00 EST          | 12.8 | 96.1  | 805        |
| 2024-01-27 01:00:00 EST          | 5.6  | 95.9  | 800        |
| 2024-04-12 09:00:00 EDT          | 12.8 | 96.1  | 402        |
| 2024-04-12 10:00:00 EDT          | 13.0 | 100.0 | 402        |
| 2024-05-06 06:00:00 EDT          | 11.1 | 96.7  | 402        |
| 2024-05-06 07:00:00 EDT          | 11.7 | 96.1  | 1609       |
| 2024-05-06 08:00:00 EDT          | 11.7 | 96.1  | 1600       |


# Multi-Station Comparison

Compare weather patterns across nearby stations:


``` python
# 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)

| id | name | mean_temp | std_temp | min_temp | max_temp | num_obs |
|----|----|----|----|----|----|----|
| str | str | f64 | f64 | f64 | f64 | u32 |
| "725020-14734" | "NEWARK LIBERTY INTERNATIONAL A… | 14.727874 | 9.630412 | -11.7 | 37.2 | 13099 |
| "725030-14732" | "LA GUARDIA AIRPORT" | 14.157531 | 9.100941 | -11.1 | 35.6 | 13420 |
| "744860-94789" | "JOHN F KENNEDY INTERNATIONAL A… | 13.798241 | 8.890841 | -10.6 | 34.4 | 13052 |


## Temperature Differences


``` python
# 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


# Historical Trends

Analyze long-term climate trends:


``` python
# Get multiple years of data
years = [2022, 2023, 2024]
historical = wv.get_weather_data("725030-14732", years=years)

# Annual average temperatures
annual = historical.group_by(pl.col("time").dt.year()).agg([
    pl.col("temp").mean().alias("mean_temp"),
    pl.col("temp").min().alias("min_temp"),
    pl.col("temp").max().alias("max_temp"),
]).sort("time")

annual
```


shape: (3, 4)

| time | mean_temp | min_temp | max_temp |
|------|-----------|----------|----------|
| i32  | f64       | f64      | f64      |
| 2022 | 13.602764 | -13.9    | 36.1     |
| 2023 | 14.439439 | -15.0    | 35.0     |
| 2024 | 14.157531 | -11.1    | 35.6     |


## Warming Trends


``` python
# Calculate linear trend (simplified)
annual_means = annual["mean_temp"].to_list()
years_numeric = list(range(len(annual_means)))

# Simple difference between first and last 5 years
first_5_years = sum(annual_means[:5]) / 5
last_5_years = sum(annual_means[-5:]) / 5

print(f"First 5 years average: {first_5_years:.2f}°C")
print(f"Last 5 years average: {last_5_years:.2f}°C")
print(f"Change: {last_5_years - first_5_years:+.2f}°C")
```


    First 5 years average: 8.44°C
    Last 5 years average: 8.44°C
    Change: +0.00°C


# Extreme Weather Events


## Heat Waves

Identify prolonged periods of high temperatures:


``` python
# 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)

| time                             | max_temp |
|----------------------------------|----------|
| datetime\[μs, America/New_York\] | f64      |
| 2024-06-19 00:00:00 EDT          | 31.7     |
| 2024-06-20 00:00:00 EDT          | 33.3     |
| 2024-06-21 00:00:00 EDT          | 35.6     |
| 2024-06-22 00:00:00 EDT          | 33.9     |
| 2024-06-23 00:00:00 EDT          | 34.4     |
| 2024-06-25 00:00:00 EDT          | 32.2     |
| 2024-06-26 00:00:00 EDT          | 32.8     |
| 2024-06-30 00:00:00 EDT          | 30.6     |
| 2024-07-05 00:00:00 EDT          | 31.1     |
| 2024-07-06 00:00:00 EDT          | 32.2     |


## Cold Snaps


``` python
# 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)

| time                             | min_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


``` python
# 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


``` python
# 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)

| variable     | completeness\_% |
|--------------|-----------------|
| str          | f64             |
| "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:


``` python
# 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

- explore the [API Reference](../reference/index.md) for detailed function documentation
- check the [GitHub repository](https://github.com/rich-iannone/weathervault) for more examples
- report issues or contribute at [github.com/rich-iannone/weathervault](https://github.com/rich-iannone/weathervault)
