---------------------------------------------------------------------- This is the API documentation for the weathervault library. ---------------------------------------------------------------------- ## Core Functions Primary functions for retrieving weather data and station information. get_weather_data(station_id: 'str', years: 'int | list[int] | None' = None, *, convert_to_local: 'bool' = True, temp_unit: 'str' = 'celsius', make_hourly: 'bool' = False, cache_dir: 'str | Path | None' = None, incl_stn_info: 'bool' = False, time_as_columns: 'bool' = False, quiet: 'bool' = False) -> 'pl.DataFrame' Get weather data for a meteorological station. Downloads and parses weather observation data from NOAA's Integrated Surface Database (ISD) for the specified station and years. Parameters ---------- station_id Station identifier in USAF-WBAN format (e.g., "725030-14732"). Use `search_stations()` or `get_station_metadata()` to find station IDs. years Year or list of years to retrieve data for. If `None`, retrieves all available years for the station. convert_to_local Whether to convert times from UTC to the station's local time. Default is `True`. temp_unit Temperature unit for output. Accepts `"c"`/`"celsius"`, `"f"`/`"fahrenheit"`, or `"k"`/`"kelvin"` (case-insensitive). Default is `"c"` (Celsius). make_hourly If `True`, resample data to hourly intervals, taking the first observation of each hour and filling missing hours with `None` values. Default is `False`. cache_dir Directory to cache downloaded data files. Options are: (1) `None` (default) for downloading data to memory without saving to disk (will check current working directory for existing cached files first), (2) `"."` saves to and loads from current working directory, and (3) a path string serving as a custom directory path for caching files. Cached files are named as `"{station_id}-{year}.gz"`. incl_stn_info Whether to include station metadata in the output. When True, adds columns for station name, country, state, ICAO code, latitude, longitude, and elevation. Default is `False`. time_as_columns If `True`, output separate columns for time components (`year`, `month`, `day`, `hour`, `min`) instead of a single `time` column. Default is `False`. quiet If `True`, suppress warning messages about partial data availability (when some requested years are not available). Default is `False`. Returns ------- pl.DataFrame A DataFrame with weather observations. Columns ------- The returned DataFrame contains the following columns: - `id`: Station identifier - `time`: Observation time (local time if `convert_to_local=True`, else UTC); or if `time_as_columns=True`: `year`, `month`, `day`, `hour`, `min` columns instead - `temp`: Air temperature (Celsius, Fahrenheit, or Kelvin based on `temp_unit=`) - `dew_point`: Dew point temperature - `rh`: Relative humidity (percentage) - `wd`: Wind direction in degrees (`0`-`360`, direction wind is blowing from) - `ws`: Wind speed in meters per second - `atmos_pres`: Atmospheric pressure at sea level (hectopascals) - `ceil_hgt`: Ceiling height in meters (`22000` is taken as unlimited) - `visibility`: Visibility in meters (max is `16000`) When `incl_stn_info=True`, the following station information columns are also included: - `name`: Station name - `country`: Country name - `state`: State/region code (if applicable) - `icao`: ICAO identifier - `lat`: Latitude in degrees - `lon`: Longitude in degrees - `elev`: Elevation in meters above sea level Examples -------- Get weather data for JFK Airport (New York) for 2023: ```{python} import weathervault as wv weather = wv.get_weather_data("744860-94789", years=2023) weather.head() ``` Get data for multiple years with Fahrenheit temperatures: ```{python} weather = wv.get_weather_data( "725030-14732", # LaGuardia Airport years=2023, temp_unit="fahrenheit" ) weather ``` Get hourly data (resampled): ```{python} weather = wv.get_weather_data( "724050-13743", # Washington Reagan Airport years=2023, make_hourly=True ) weather ``` Cache data to current directory for offline use: ```{python} weather = wv.get_weather_data( "725030-14732", years=2023, cache_dir="." # Saves to current working directory ) # Subsequent calls will automatically use the cached file weather = wv.get_weather_data("725030-14732", years=2023) # Loads from cache weather ``` Include station metadata in the output: ```{python} weather = wv.get_weather_data( "725030-14732", years=2023, incl_stn_info=True ) weather[["name", "country", "lat", "lon"]].head(1) ``` get_station_metadata(*, include_timezone: 'bool' = True, force_refresh: 'bool' = False) -> 'pl.DataFrame' Get metadata for all weather stations. Downloads and parses the ISD history file containing information about all weather stations in the database. Parameters ---------- include_timezone Whether to look up timezone names based on station coordinates. This adds a `tz_name` column. Default is `True`. force_refresh Force re-download of station data even if cached. Default is `False`. Returns ------- pl.DataFrame A DataFrame with station metadata. Columns ------- The returned DataFrame contains the following columns: - `id`: Station ID (USAF-WBAN format) - `usaf`: USAF station identifier - `wban`: WBAN station identifier - `name`: Station name - `country_code`: ISO 3166-1 alpha-2 country code - `country`: Country name - `state`: US state code (if applicable) - `icao`: ICAO identifier - `lat`: Latitude in degrees - `lon`: Longitude in degrees - `elev`: Elevation in meters - `begin_date`: Date of first available data - `end_date`: Date of last available data - `tz_name`: Timezone name (only included if `include_timezone=True`) Examples -------- Get metadata for all weather stations: ```{python} import weathervault as wv stations = wv.get_station_metadata() stations.head() ``` search_stations(*, name: 'str | None' = None, country: 'str | None' = None, country_code: 'str | None' = None, state: 'str | None' = None, lat_range: 'tuple[float, float] | None' = None, lon_range: 'tuple[float, float] | None' = None, has_recent_data: 'bool' = False) -> 'pl.DataFrame' Search for weather stations matching specified criteria. Parameters ---------- name Search for stations with names containing this string (case-insensitive). country Filter by country name (case-insensitive, partial match). country_code Filter by ISO 3166-1 alpha-2 country code (e.g., `"US"`, `"GB"`, `"FR"`). For convenience, you can also use the `wv.country` shorthand: `wv.country.US`, `wv.country.GB`, `wv.country.DE`, etc. state Filter by US state or territory code (exact match, e.g., `"CA"`, `"NY"`, `"TX"`). For convenience, you can also use the `wv.state` shorthand: `wv.state.CA`, `wv.state.NY`, `wv.state.TX`, etc. lat_range Filter by latitude range as (min_lat, max_lat). lon_range Filter by longitude range as (min_lon, max_lon). has_recent_data If `True`, only return stations with data in the current or previous year. Returns ------- pl.DataFrame A DataFrame of stations matching the search criteria. Examples -------- Search for stations in California using the state shorthand: ```{python} import weathervault as wv # Using wv.state shorthand (provides autocomplete) ca_stations = wv.search_stations(state=wv.state.CA) ca_stations ``` Search by country code using the convenient shorthand: ```{python} # Using wv.country shorthand (provides autocomplete) de_stations = wv.search_stations(country_code=wv.country.DE) de_stations ``` Combine state and country filters: ```{python} # Find stations in California, US us_ca = wv.search_stations( country_code=wv.country.US, state=wv.state.CA ) us_ca ``` Search for stations within a bounding box: ```{python} within = wv.search_stations( lat_range=(37.0, 38.0), lon_range=(-122.5, -121.5) ) within ``` ## Station Discovery Functions for exploring available stations and their data coverage. get_inventory(*, force_refresh: 'bool' = False) -> 'pl.DataFrame' Get the data inventory for all stations and years. Downloads and parses the ISD inventory file containing record counts for each station by year and month. Parameters ---------- force_refresh Force re-download of inventory data even if cached. Default is `False`. Returns ------- pl.DataFrame A DataFrame with inventory information. Columns ------- The returned DataFrame contains the following columns: - `id`: Station ID (USAF-WBAN format) - `usaf`: USAF station identifier - `wban`: WBAN station identifier - `year`: Year of data - `jan` through `dec`: Record counts for each month - `total`: Total records for the year Examples -------- Get data inventory for all stations: ```{python} import weathervault as wv import polars as pl inventory = wv.get_inventory() inventory.filter(pl.col("id") == "725030-14732") ``` get_years_for_station(station_id: 'str') -> 'list[int]' Get the list of years for which a station has data. Parameters ---------- station_id The station ID in USAF-WBAN format (e.g., `"725030-14732"`). Returns ------- list[int] List of years with available data. Examples -------- Get available years for a specific station: ```{python} import weathervault as wv years = wv.get_years_for_station("725030-14732") years ``` get_countries() -> 'pl.DataFrame' Get a DataFrame of country codes and names. Returns ------- pl.DataFrame A DataFrame with country information. Columns ------- The returned DataFrame contains the following columns: - `country_code`: ISO 3166-1 alpha-2 country code - `country`: Country name Examples -------- Get a list of all countries with weather stations: ```{python} import weathervault as wv countries = wv.get_countries() countries ``` ## Helper Objects Convenience objects for station and location lookups with autocomplete support. station Helper object for accessing weather station IDs with autocomplete. Provides hierarchical attribute-based access to weather station IDs organized by country and state (for US stations). Station data is loaded lazily on first access. Stations are organized using ISO 3166-1 alpha-2 country codes: - For US stations: `station.US..` - For other countries: `station..` Example: >>> import weathervault as wv >>> # Access a specific US station by state: >>> station_id = wv.station.US.NY.LAGUARDIA_AP >>> station_id '725030-14732' >>> # Access a non-US station: >>> wv.station.DE.BERLIN_TEGEL # Germany '103820-99999' >>> # Search for stations by name pattern: >>> wv.station.search('laguardia') {'US.NY.LAGUARDIA_AP': '725030-14732'} >>> # Autocomplete shows available countries/states/stations >>> wv.station.US. # <-- IDE will show state codes >>> wv.station.US.CA. # <-- IDE will show California stations See Also: `get_station_metadata()` : Get full metadata for all stations. `search_stations()` : Search stations by criteria. country Helper object for accessing ISO 3166-1 alpha-2 country codes with autocomplete. Provides attribute-based access to all ISO country codes for convenient use in function calls. Each country code is available as an attribute (e.g., `country.US`, `country.DE`, `country.GB`). Example: >>> import weathervault as wv >>> # Use with search_stations: >>> wv.search_stations(country_code=wv.country.DE) >>> wv.search_stations(country_code=wv.country.GB) >>> # Autocomplete shows all available country codes >>> wv.country. # <-- IDE will show suggestions like US, GB, DE, etc. See Also: `ISO_COUNTRY_NAMES` : Dictionary of all ISO country codes and names. state Helper object for accessing US state and territory codes with autocomplete. Provides attribute-based access to all US state and territory codes for convenient use in function calls. Each state code is available as an attribute (e.g., `state.CA`, `state.NY`, `state.TX`). Includes all 50 US states, District of Columbia, and 5 US territories (American Samoa, Guam, Northern Mariana Islands, Puerto Rico, U.S. Virgin Islands). Example: >>> import weathervault as wv >>> # Use with search_stations: >>> wv.search_stations(country_code='US', state=wv.state.CA) >>> wv.search_stations(country_code='US', state=wv.state.NY) >>> # Autocomplete shows all available state codes >>> wv.state. # <-- IDE will show suggestions like CA, NY, TX, etc. See Also: `US_STATE_NAMES` : Dictionary of all US state codes and names. ## Constants Data constants and URL configurations used by the package. BASE_URL str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'. COUNTRY_CODES dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) ISO_COUNTRY_NAMES dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) US_STATE_NAMES dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) ---------------------------------------------------------------------- This is the User Guide documentation for the package. ---------------------------------------------------------------------- ### Introduction **weathervault** is a Python package for obtaining historical weather data from NOAA's National Centers for Environmental Information (NCEI) Integrated Surface Database (ISD). It provides a simple, intuitive API for downloading and processing weather station data, returning results as efficient Polars DataFrames ready for analysis. ## Key Features - **Simple API**: Download weather data with a single function call - **Polars DataFrames**: Get data as efficient, fast DataFrames optimized for analysis - **Station Discovery**: Find weather stations by name, location, elevation, and more - **Automatic Time Conversion**: Convert UTC timestamps to local station time automatically - **Temperature Units**: Support for Celsius, Fahrenheit, and Kelvin - **Local Caching**: Optional file caching to avoid re-downloading data - **Global Coverage**: Access to the ISD network with 29,000+ weather stations worldwide ## What is the Integrated Surface Database? The [Integrated Surface Database (ISD)](https://www.ncei.noaa.gov/products/land-based-station/integrated-surface-database) is NOAA's comprehensive archive of hourly and synoptic surface weather observations from around the world. It contains data from: - Airport weather stations (METAR data) - Land-based weather observation sites - Marine weather buoys and ships - Military installations The database spans from 1901 to present, with most stations having data from the 1970s onward. ## Data Variables weathervault provides access to the following weather variables: | Variable | Description | Units | |----------|-------------|-------| | `temp` | Air temperature | °C (default), °F, or K | | `dew_point` | Dew point temperature | °C (default), °F, or K | | `rh` | Relative humidity | % | | `wd` | Wind direction | degrees (0-360) | | `ws` | Wind speed | m/s | | `atmos_pres` | Atmospheric pressure | hPa | | `ceil_hgt` | Ceiling height | meters | | `visibility` | Visibility distance | meters | ## Installation Install weathervault from PyPI: ```bash pip install weathervault ``` Or install from the latest GitHub source: ```bash pip install git+https://github.com/rich-iannone/weathervault.git ``` ## Quick Example Here's how to get weather data for LaGuardia Airport in New York for the year 2024: ```python import weathervault as wv # Get weather data weather = wv.get_weather_data("725030-14732", years=2024) weather ``` The result is a Polars DataFrame with timestamps automatically converted to the station's local timezone (America/New_York): ``` shape: (13_420, 10) ┌──────────────┬────────────────────────────────┬──────┬───────────┬──────┐ │ id ┆ time ┆ temp ┆ dew_point ┆ rh │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ datetime[μs, America/New_York] ┆ f64 ┆ f64 ┆ f64 │ ╞══════════════╪════════════════════════════════╪══════╪═══════════╪══════╡ │ 725030-14732 ┆ 2024-01-01 00:51:00 EST ┆ 6.1 ┆ -2.8 ┆ 52.9 │ │ 725030-14732 ┆ 2024-01-01 01:00:00 EST ┆ 6.1 ┆ -2.8 ┆ 52.9 │ │ 725030-14732 ┆ 2024-01-01 01:51:00 EST ┆ 6.1 ┆ -2.8 ┆ 52.9 │ │ … ┆ … ┆ … ┆ … ┆ … │ └──────────────┴────────────────────────────────┴──────┴───────────┴──────┘ ``` ## Next Steps Continue reading to learn more: - [Finding Stations](02-finding-stations.html) – Discover weather stations by location, name, and attributes - [Getting Weather Data](03-getting-data.html) – Download and customize weather data - [Data Processing](04-data-processing.html) – Work with timestamps, units, and hourly data - [Examples](05-examples.html) – Real-world analysis examples ### Finding Weather Stations Before you can download weather data, you need to know the station ID. weathervault provides several functions to help you discover weather stations. ## Station Metadata The `get_station_metadata()` function returns information about all weather stations in the ISD network: ```{python} import weathervault as wv # Get metadata for all stations stations = wv.get_station_metadata() stations ``` The returned DataFrame contains: - `id` – Station identifier in USAF-WBAN format - `usaf` – USAF station number - `wban` – WBAN station number - `name` – Station name - `country_code` – FIPS country code - `country` – Country name - `state` – State/province (US/CA stations) - `icao` – ICAO airport code (if applicable) - `lat`, `lon` – Station coordinates - `elev` – Elevation in meters - `begin_date`, `end_date` – Period of record - `tz_name` – IANA timezone name ## Searching for Stations The `search_stations()` function lets you filter stations by various criteria: ### By Country Use the convenient `wv.country` shorthand for clean, readable code with IDE autocomplete: ```{python} # Find all stations in Germany de_stations = wv.search_stations(country_code=wv.country.DE) de_stations ``` You can also search by country name: ```{python} # Find stations in Japan japan_stations = wv.search_stations(country="Japan") japan_stations ``` ### By US State For US stations, use the `wv.state` shorthand: ```{python} # Find stations in California ca_stations = wv.search_stations(state=wv.state.CA) ca_stations ``` Multiple states can be searched at once: ```{python} # Find stations in California california = wv.search_stations(state=wv.state.CA) california ``` ### By Geographic Bounding Box Search for stations within a latitude/longitude range: ```{python} # Find stations in the New York City area nyc_stations = wv.search_stations( lat_range=(40.5, 41.0), lon_range=(-74.5, -73.5) ) nyc_stations ``` This is useful for: - Finding all stations in a specific region - Identifying nearby stations for spatial analysis - Creating regional datasets ### By Station Name Search by station name (case-insensitive, partial matching): ```{python} # Find Tokyo International Airport tokyo_airports = wv.search_stations(name="tokyo international") tokyo_airports ``` ```{python} # Find all "LaGuardia" stations lga = wv.search_stations(name="laguardia") lga ``` ### Combined Searches You can combine multiple search criteria: ```{python} # Find California airports with "international" in the name ca_intl_airports = wv.search_stations( state=wv.state.CA, name="international" ) ca_intl_airports ``` ```{python} # Find German stations in a specific region region_de = wv.search_stations( country_code=wv.country.DE, lat_range=(50.0, 52.0), lon_range=(8.0, 10.0) ) region_de ``` ## Checking Available Years Once you've found a station, use `get_years_for_station()` to see what years have data: ```{python} # Check available years for LaGuardia Airport years = wv.get_years_for_station("725030-14732") print(f"Data available: {min(years)} to {max(years)}") print(f"Total years: {len(years)}") ``` ## Station Inventory Details For more detailed information about data availability, use `get_inventory()`: ```{python} import polars as pl # Get detailed inventory for a station inventory = wv.get_inventory() station_inv = inventory.filter(pl.col("id") == "725030-14732") station_inv ``` This returns monthly observation counts, useful for assessing data completeness before downloading. ## Using the Station Registry weathervault includes a convenient registry for accessing commonly used stations hierarchically: ```{python} # Access US stations by state and name laguardia = wv.station.us.ny.la_guardia_airport print(f"Station ID: {laguardia}") ``` ```{python} # Access international stations # For non-US stations, use search_stations to find them munich = wv.search_stations(name="MUNICH", country="Germany").head(1) munich ``` The registry provides: - IDE autocomplete for easy station discovery - hierarchical organization (country -> state/region -> station) - sanitized names (spaces replaced with underscores, lowercased) To explore available stations in the registry: ```python # See available countries dir(wv.station) ``` ```python # See US states dir(wv.station.us) ``` ```python # See stations in New York dir(wv.station.us.ny) ``` ## Country and State Codes weathervault provides convenient access to country and US state codes: ### Country Codes ```{python} # List all available countries countries = wv.get_countries() countries ``` ### Access Country Codes ```{python} # Get code for a country wv.country.FR # France wv.country.JP # Japan wv.country.GB # United Kingdom ``` ### US State Codes ```{python} # Access US state codes wv.state.NY # New York wv.state.TX # Texas wv.state.HI # Hawaii ``` These shorthands make your code more readable and provide IDE autocomplete support. ## Tips for Finding Stations When searching for weather stations, start broad, then narrow your search (begin with a geographic search or country filter, then refine by name). Always check data availability by verifying years and data completeness before large downloads. Keep in mind that many airports have multiple station IDs representing different time periods, and stations at similar locations may have overlapping coverage. Generally, newer stations often have more complete data than historical ones. ## Next Steps Now that you know how to find stations, learn how to [get weather data](03-getting-data.html). ### Getting Weather Data The `get_weather_data()` function is the main interface for downloading weather observations from the ISD database. ## Basic Usage At minimum, you need a station ID: ```{python} import weathervault as wv # Get all available data for a station weather = wv.get_weather_data("725030-14732") weather ``` By default, this downloads all available years for the station. ## Specifying Years ### Single Year ```{python} # Get data for 2024 weather_2024 = wv.get_weather_data("725030-14732", years=2024) weather_2024 ``` ### Multiple Years ```{python} # Get data for specific years weather_range = wv.get_weather_data("725030-14732", years=[2023, 2024]) weather_range ``` ```{python} # Get a range of years years = [2023, 2024] weather_multi = wv.get_weather_data("725030-14732", years=years) weather_multi ``` ## Temperature Units By default, temperatures are in Celsius. You can change this with the `temp_unit` parameter: ```{python} # Fahrenheit weather_f = wv.get_weather_data("725030-14732", years=2024, temp_unit="fahrenheit") ``` ```{python} # Kelvin weather_k = wv.get_weather_data("725030-14732", years=2024, temp_unit="kelvin") ``` Short forms are also supported: ```{python} wv.get_weather_data("725030-14732", years=2024, temp_unit="f") # Fahrenheit wv.get_weather_data("725030-14732", years=2024, temp_unit="c") # Celsius wv.get_weather_data("725030-14732", years=2024, temp_unit="k") # Kelvin ``` ## Time Conversion ### Local Time (Default) By default, timestamps are converted from UTC to the station's local timezone: ```{python} # Times in America/New_York timezone weather_local = wv.get_weather_data("725030-14732", years=2024) print(weather_local["time"].dtype) # datetime[μs, America/New_York] ``` This handles: - daylight saving time transitions - timezone offsets - year boundaries (buffer years are automatically fetched) ### UTC Time To keep timestamps in UTC: ```{python} # Times in UTC weather_utc = wv.get_weather_data( "725030-14732", years=2024, convert_to_local=False ) print(weather_utc["time"].dtype) # datetime[μs, UTC] ``` ## Hourly Resampling Weather observations are typically irregular (every hour, but sometimes more or less frequent). Use `make_hourly=True` to resample to exact hourly intervals: ```{python} # Resample to hourly data weather_hourly = wv.get_weather_data( "725030-14732", years=2024, make_hourly=True ) # All observations at exact hours print(weather_hourly["time"].dt.minute().unique()) # [0] ``` This creates a complete hourly time series, with missing hours filled in as `null` values. ## Including Station Metadata Add station information columns to each row: ```{python} # Include station name, location, etc. weather_with_info = wv.get_weather_data( "725030-14732", years=2024, incl_stn_info=True ) # Additional columns: name, country, state, icao, lat, lon, elev weather_with_info[["id", "name", "lat", "lon", "elev"]] ``` This is useful when combining data from multiple stations. ## Time as Separate Columns For some analyses, you may want time broken into year/month/day/hour/minute columns: ```{python} # Split datetime into components weather_split = wv.get_weather_data( "725030-14732", years=2024, time_as_columns=True ) # Columns: id, year, month, day, hour, min, temp, ... weather_split[["year", "month", "day", "hour", "min"]] ``` ## Local Caching To avoid re-downloading data, use local file caching: ```{python} # Cache files in a specific directory weather = wv.get_weather_data( "725030-14732", years=2024, cache_dir="./weather_cache" ) ``` Subsequent calls will use cached files if available. To use the current directory: ```{python} # Cache in current working directory weather = wv.get_weather_data("725030-14732", years=2024, cache_dir=".") ``` ## Quiet Mode Suppress warnings about partial data: ```{python} # No warnings about unavailable years weather = wv.get_weather_data( "725030-14732", years=[2020, 2021, 2022, 2023, 2024], quiet=True ) ``` ## Error Handling ### Invalid Station ```{python} try: weather = wv.get_weather_data("000000-00000", years=2024) except ValueError as e: print(f"Error: {e}") # Error: Station '000000-00000' not found in station metadata ``` ### Unavailable Years ```{python} try: weather = wv.get_weather_data("725030-14732", years=1800) except ValueError as e: print(f"Error: {e}") # Error includes available year range ``` ### Partial Data If some requested years are unavailable, weathervault warns you and returns the available years: ```{python} # Request years that don't have data - raises ValueError try: weather = wv.get_weather_data("725030-14732", years=list(range(1900, 1951))) except ValueError as e: print(f"Error: {str(e)[:150]}...") ``` ## Complete Example Here's a typical workflow combining multiple options: ```{python} import weathervault as wv import polars as pl # Get weather data with custom options weather = wv.get_weather_data( "725030-14732", # LaGuardia Airport years=2024, temp_unit="celsius", make_hourly=True, incl_stn_info=True, cache_dir="./cache" ) # Quick analysis temp_stats = weather.select([ pl.col("temp").mean().alias("mean_temp"), pl.col("temp").min().alias("min_temp"), pl.col("temp").max().alias("max_temp"), ]) print(temp_stats) ``` ## Performance Tips For best performance, always use caching by specifying `cache_dir=` for repeated downloads (this avoids re-downloading the same data). Request specific years rather than downloading all available years if you only need recent data. When working with multiple years, batch your requests by downloading them in one call rather than making separate calls. Finally, if you don't need timezone conversion, set `convert_to_local=False` to avoid the local time overhead associated with timezone calculations. ## Next Steps Learn about [data processing and analysis](04-data-processing.html) with weathervault. ### Data Processing Once you have weather data, Polars provides powerful tools for analysis. This guide shows common data processing patterns. ## Working with Polars DataFrames weathervault returns [Polars DataFrames](https://pola-rs.github.io/polars/), which offer: - fast performance (written in Rust) - expressive API similar to pandas - lazy evaluation support - excellent datetime handling ```{python} import weathervault as wv import polars as pl weather = wv.get_weather_data("725030-14732", years=2024) ``` ## Basic DataFrame Operations ### Inspecting Data ```{python} # Shape print(weather.shape) # Column names and types print(weather.schema) # First few rows weather.head() # Summary statistics weather.describe() ``` ### Selecting Columns ```{python} # Select specific columns temps = weather.select(["time", "temp", "dew_point"]) temps ``` ```{python} # Select multiple columns with expressions weather.select([ pl.col("time"), pl.col("temp"), pl.col("ws").alias("wind_speed") ]) ``` ### Filtering Rows ```{python} # Filter by temperature hot_days = weather.filter(pl.col("temp") > 30) hot_days ``` ```{python} # Multiple conditions summer_hot = weather.filter( (pl.col("temp") > 25) & (pl.col("time").dt.month().is_in([6, 7, 8])) ) summer_hot ``` ```{python} # Filter non-null values complete_data = weather.filter( pl.col("temp").is_not_null() & pl.col("ws").is_not_null() ) complete_data ``` ## Time-Based Analysis ### Extract Time Components ```{python} # Add time components as new columns weather_with_time = weather.with_columns([ pl.col("time").dt.year().alias("year"), pl.col("time").dt.month().alias("month"), pl.col("time").dt.day().alias("day"), pl.col("time").dt.hour().alias("hour"), pl.col("time").dt.weekday().alias("weekday"), ]) weather_with_time[["time", "year", "month", "day", "hour"]] ``` ### Filter by Time Range ```{python} # Filter to a date range by extracting the date component jan_2024 = weather.filter( (pl.col("time").dt.date() >= pl.date(2024, 1, 1)) & (pl.col("time").dt.date() < pl.date(2024, 2, 1)) ) jan_2024 ``` ### Resample to Different Time Intervals ```{python} # Daily aggregation daily = weather.group_by_dynamic("time", every="1d").agg([ pl.col("temp").mean().alias("mean_temp"), pl.col("temp").min().alias("min_temp"), pl.col("temp").max().alias("max_temp"), pl.col("ws").mean().alias("mean_wind_speed"), ]) daily ``` ```{python} # Monthly aggregation 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"), pl.col("rh").mean().alias("mean_humidity"), ]) monthly ``` ## Handling Missing Values ### Identify Missing Data ```{python} # Count nulls per column null_counts = weather.null_count() null_counts ``` ```{python} # Percentage of missing values missing_pct = (weather.null_count() / weather.height) * 100 missing_pct ``` ### Fill Missing Values ```{python} # Forward fill weather_filled = weather.with_columns([ pl.col("temp").forward_fill().alias("temp_filled") ]) ``` ```{python} # Fill with a specific value weather_filled = weather.with_columns([ pl.col("temp").fill_null(0) ]) ``` ```{python} # Drop rows with any null values weather_complete = weather.drop_nulls() ``` ## Temperature Conversions While weathervault supports built-in temperature unit conversion, you can also convert manually: ```{python} # Celsius to Fahrenheit weather_manual = weather.with_columns([ ((pl.col("temp") * 9 / 5) + 32).alias("temp_f") ]) weather_manual[["temp", "temp_f"]] ``` ```{python} # Celsius to Kelvin weather_manual = weather.with_columns([ (pl.col("temp") + 273.15).alias("temp_k") ]) weather_manual[["temp", "temp_k"]] ``` ## Aggregations and Statistics ### Basic Statistics ```{python} # Calculate statistics for each numeric column weather.select([ pl.col("temp").mean().alias("mean_temp"), pl.col("temp").median().alias("median_temp"), pl.col("temp").std().alias("std_temp"), pl.col("temp").quantile(0.25).alias("q25_temp"), pl.col("temp").quantile(0.75).alias("q75_temp"), ]) ``` ### Group By Operations ```{python} # Monthly statistics monthly_stats = weather.group_by(pl.col("time").dt.month()).agg([ pl.col("temp").mean().alias("mean_temp"), pl.col("temp").min().alias("min_temp"), pl.col("temp").max().alias("max_temp"), pl.col("rh").mean().alias("mean_humidity"), pl.col("ws").mean().alias("mean_wind_speed"), pl.len().alias("num_observations"), ]) monthly_stats.sort("time") ``` ```{python} # Hourly patterns (average conditions by hour of day) hourly_pattern = weather.group_by(pl.col("time").dt.hour()).agg([ pl.col("temp").mean().alias("mean_temp"), pl.col("ws").mean().alias("mean_wind_speed"), ]).sort("time") hourly_pattern ``` ## Combining Multiple Stations When analyzing multiple stations, you'll want to combine their data: ```{python} # Get data from multiple stations 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) # Concatenate vertically nyc_airports = pl.concat([lga, jfk, ewr]) # Compare average temperatures comparison = nyc_airports.group_by(["id", "name"]).agg([ pl.col("temp").mean().alias("mean_temp"), pl.col("temp").min().alias("min_temp"), pl.col("temp").max().alias("max_temp"), ]) comparison ``` ## Exporting Data ### To CSV ```python # Save to CSV weather.write_csv("weather_data.csv") ``` ### To Parquet ```python # Save to Parquet (more efficient for large datasets) weather.write_parquet("weather_data.parquet") ``` ### To Pandas weathervault uses Polars DataFrames natively. If you need pandas compatibility, use `df.to_pandas()` (requires pyarrow). ## Data Quality Checks ### Identify Extreme Values ```{python} # Find extreme temperatures extreme_temps = weather.filter( (pl.col("temp") < -40) | (pl.col("temp") > 50) ) if extreme_temps.height > 0: print(f"Found {extreme_temps.height} extreme temperature values") extreme_temps[["time", "temp"]] ``` ### Check for Duplicate Timestamps ```{python} # Find duplicate times duplicates = weather.filter( pl.col("time").is_duplicated() ) print(f"Duplicate timestamps: {duplicates.height}") ``` ### Data Completeness Report ```{python} # Create a completeness report completeness = pl.DataFrame({ "variable": weather.columns, "total_obs": [weather.height] * len(weather.columns), "missing": [weather[col].null_count() for col in weather.columns], }).with_columns([ (100 - (pl.col("missing") / pl.col("total_obs") * 100)).alias("completeness_pct") ]) completeness ``` ## Advanced: Lazy Evaluation For very large datasets, use Polars lazy API: ```{python} # Create a lazy query lazy_weather = weather.lazy() # Build a query (not executed yet) result_lazy = ( lazy_weather .filter(pl.col("temp").is_not_null()) .group_by_dynamic("time", every="1d") .agg([ pl.col("temp").mean().alias("mean_temp"), pl.col("temp").max().alias("max_temp"), ]) ) # Execute when needed result = result_lazy.collect() result ``` ## Performance Tips For optimal performance, use Polars native operations instead of Python loops (vectorized operations are significantly faster). Always filter early by applying filters before aggregations to reduce data size. For complex queries on large datasets, consider using lazy evaluation with `.lazy()` to optimize the query execution plan. When saving or loading large datasets, prefer Parquet format over CSV as it's much faster and more efficient. Finally, select only the columns you need rather than loading entire datasets into memory. ## Next Steps See [practical examples](05-examples.html) of weather data analysis with weathervault. ### 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) ``` ### 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 ``` ### 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 ``` ## 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) ``` ### 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)) ``` ### 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}") ``` ## 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 ``` ### 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) ``` ## 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) ``` ## 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 ``` ### 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") ``` ## 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 ``` ### 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") ``` ## 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) ``` ### 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) ``` ## 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()) ``` ### 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 ``` ## 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.html) 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)