Skip to content

h3 — H3 index

Every example on this page starts here

import polars as pl
import polars_hash as plh

The H3 cell index, on pl.Expr as .h3.

H3 is the hierarchical hexagonal grid from Uber. Refer to the H3 website. H3 divides the earth into hexagons, where a geohash uses rectangles. Each hexagonal cell has six neighbors and the distance to each neighbor is the same, so H3 is better than a geohash for aggregation and area analysis. A geohash keeps the more simple property that a prefix gives a rectangular area.

Note

This namespace encodes only. To decode a cell index or to find the neighbors of a cell, use the h3 Python package on the output column. The geohash namespace has both operations.

from_coords

from_coords(len: int = 12) -> Expr

Encode a coordinate struct to an H3 cell index.

The input is the Struct that geohash reads, a latitude field and a longitude field, both float.

Parameters:

Name Type Description Default
len int

The H3 resolution, from 1 to 15. A column name or a pl.Expr also works at run time and gives one resolution for each row, but the type hint does not show this yet. polars-hash casts the value to Int64. Resolution 0 is not permitted, although H3 has it: it has 122 base cells and is not a usual level for aggregation.

12

Returns:

Type Description
Expr

Utf8, the standard lowercase hexadecimal cell index with 15 characters. The value holds the resolution, so two indexes of different resolutions are always different.

Raises:

Type Description
ComputeError

len is less than 1 or more than 15 (expected resolution between 1 and 15, got 16); len is null (Length may not be null); a coordinate is outside its range or is NaN or infinite (invalid coordinate range: latitude 91, longitude -120.6623); or a coordinate field is not a float (Latitude input needs to be float). A null latitude or a null longitude gives null for that row, and raises nothing.

Note

The approximate average edge length of a hexagon: resolution 1 gives 483 km, 3 gives 69 km, 5 gives 9.9 km, 7 gives 1.4 km, 9 gives 200 m, 11 gives 29 m, 13 gives 4.1 m, and 15 gives 0.6 m.

Examples:

>>> df = pl.DataFrame(
...     {"coord": [{"longitude": -120.6623, "latitude": 35.3003}]},
...     schema={
...         "coord": pl.Struct(
...             [
...                 pl.Field("longitude", pl.Float64),
...                 pl.Field("latitude", pl.Float64),
...             ]
...         )
...     },
... )
>>> df.select(plh.col("coord").h3.from_coords(5)).item()
'8529adc7fffffff'