Skip to Content
cwa
Advanced

Batch queries and export

Query many locations at once and export forecasts to Polars, Pandas or Arrow.

When you need data for several townships, pass them all at once. It is much faster than one call each: townships in the same county share one request, and requests for different counties run at the same time.

Many locations

forecast.get() and weather.get() accept these forms, and key every result by township:

WriteCovers
get([Township.TAIPEI.XINYI, "花蓮市"])The listed townships
get(County.HUALIEN)Every township in the county
get([County.HUALIEN, "高雄市左營區"])Counties and townships mixed
get_all()Every township in Taiwan
from cwa import CWA, County, Township

with CWA() as client:
    forecasts = client.forecast.get(
        [Township.TAIPEI.XINYI, County.HUALIEN, "高雄市左營區"], days=3
    )

for town, forecast in forecasts.items():
    print(town.full_name, forecast.today)

xinyi = forecasts[Township.TAIPEI.XINYI]

Use the result like a dict, with items(), keys() and [township], but it cannot be modified.

Other features accept lists too, keyed by input:

MethodKeyed by
alerts.active([...])Each location
observations.nearest([...])Each location
observations.latest([...]), stations.get([...])Each station ID
quake.distance_to([...])Each location

Partial failures

By default, if any location fails the call raises BatchError. The exception keeps what finished and what failed:

AttributeContains
error.completedThe locations that succeeded
error.failuresThe failed locations and their exceptions

To keep the successful results and deal with failures later, pass errors="collect". Nothing is raised; you get a BatchResult instead:

with CWA() as client:
    result = client.forecast.get([Township.TAIPEI.XINYI, "花蓮市"], errors="collect")

for town, forecast in result.successes.items():
    print(town.full_name, forecast.today)

for town, failure in result.failures.items():
    print(town.full_name, failure.kind.__name__, failure.message)
AttributeContains
successesThe successful locations and results, as in a normal query
failuresThe failed locations and their Failure
completeTrue when everything succeeded

A Failure records the error type kind (such as NotFoundError), the message and the HTTP status. An invalid API key or client setting is not a per-location problem, so it is raised even with collect.

Export to tables

Forecasts export to Polars, Pandas or Arrow, one row per township and day:

import polars as pl
from cwa import County, forecast

daily = forecast.get(County.TAIPEI, days=3).to_polars()
rainy = daily.filter(pl.col("precipitation_max_probability") >= 50)
MethodNeedsReturns
to_polars()cwa[polars]polars.DataFrame
to_pandas()cwa[pandas]pandas.DataFrame with Arrow-backed columns; missing values are <NA>
to_arrow()cwa[arrow]pyarrow.Table

Each installs on its own and raises MissingDependencyError without its extra. Both a single Forecast and a multi-township result can be exported, and every format has the same columns and types:

ColumnTypeMeaning
township_codeStringTownship code
township, countyStringTownship and county names
dateDateTaiwan date
temperature_min, temperature_maxFloatThe low and high published by the CWA (°C)
temperature_sampled_min, temperature_sampled_maxFloatLowest and highest hourly temperature forecast (°C)
precipitation_max_probabilityIntegerThe day’s highest period probability of precipitation (%)
wind_max_speedFloatThe day’s highest wind speed (m/s)
wind_max_speed_is_lower_boundBooleanWhether that speed is only a lower bound
conditionStringThe daytime weather
as_ofDatetime (Taiwan time)Query time
source_idsList of stringsSource dataset IDs
source_retrieved_at, source_issued_at, source_updated_atList of datetimesEach source’s retrieval, issue and update time
source_stale, source_partialBooleanWhether any source was out of date or incomplete
sample_countIntegerNumber of forecast periods in the day

Columns mean the same as the daily fields; missing values are null.