Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update sorting method in ehighways renaming #398

Merged
merged 3 commits into from
Jun 21, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 14 additions & 3 deletions scripts/shapes/units.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def _build_layer(
for country, source_layer in resolution_config.items()
])
assert isinstance(layer, pd.DataFrame)
return gpd.GeoDataFrame(layer, crs=crs)
return gpd.GeoDataFrame(layer, crs=crs).reset_index(drop=True)


def _read_source_layers(
Expand Down Expand Up @@ -121,7 +121,17 @@ def _rename_ehighways_countries(units: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
Method is future-proofed to handle higher resolution than country code (e.g. using GADM3 units in one country).
It does this by ordering all non-ehighways IDs alphabetically and then turning them into "XXX_#" style codes.
"""
sorted_units = units.sort_values(by="id")
# Extract all digits from a string, merge them in order via string summation, then convert to an integer
# E.g., "BE.1.2-3" -> 123
order = (
units.id.str.extractall(r"(\d+)")
.groupby(level=0)
.sum()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not exactly clear to me what you are summing here. Maybe a comment would be helpful.

.reindex(units.index)
.fillna(1)
.astype(int)
)
sorted_units = units.assign(order=order).sort_values(by=["country_code", "order"])

new_names = (
sorted_units.country_code
Expand All @@ -132,7 +142,8 @@ def _rename_ehighways_countries(units: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
sorted_units["id"] = sorted_units.id.where(
sorted_units.type == "ehighways", new_names
)
return sorted_units

return sorted_units.drop("order", axis=1)


if __name__ == "__main__":
Expand Down