Skip to content

Commit 7ce01aa

Browse files
committed
optimize dataset creation
1 parent f9be618 commit 7ce01aa

File tree

1 file changed

+18
-16
lines changed

1 file changed

+18
-16
lines changed

cf_xarray/geometry.py

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -854,29 +854,31 @@ def polygons_to_cf(
854854
crdX = geom_coords[:, 0]
855855
crdY = geom_coords[:, 1]
856856

857+
data_vars = {names.node_count: (dim, node_count)}
858+
859+
# Special case when we have no MultiPolygons and no holes
860+
if len(part_node_count) != len(node_count):
861+
data_vars[names.part_node_count] = (names.part_dim, part_node_count)
862+
names.geometry_container_attrs["part_node_count"] = names.part_node_count
863+
864+
# Special case when we have no holes
865+
if interior_ring.any():
866+
data_vars[names.interior_ring] = (names.part_dim, interior_ring)
867+
names.geometry_container_attrs["interior_ring"] = names.interior_ring
868+
869+
data_vars[names.container_name] = (
870+
(),
871+
np.nan,
872+
{"geometry_type": "polygon", **names.geometry_container_attrs},
873+
)
857874
ds = xr.Dataset(
858-
data_vars={
859-
names.node_count: xr.DataArray(node_count, dims=(dim,)),
860-
names.container_name: xr.DataArray(
861-
data=np.nan,
862-
attrs={"geometry_type": "polygon", **names.geometry_container_attrs},
863-
),
864-
},
875+
data_vars=data_vars,
865876
coords=names.coords(x=x, y=y, crdX=crdX, crdY=crdY, dim=dim),
866877
)
867878

868879
if coord is not None:
869880
ds = ds.assign_coords({dim: coord})
870881

871-
# Special case when we have no MultiPolygons and no holes
872-
if len(part_node_count) != len(node_count):
873-
ds[names.part_node_count] = xr.DataArray(part_node_count, dims=names.part_dim)
874-
ds[names.container_name].attrs["part_node_count"] = names.part_node_count
875-
876-
# Special case when we have no holes
877-
if interior_ring.any():
878-
ds[names.interior_ring] = xr.DataArray(interior_ring, dims=names.part_dim)
879-
ds[names.container_name].attrs["interior_ring"] = names.interior_ring
880882
return ds
881883

882884

0 commit comments

Comments
 (0)