简体   繁体   中英

Convert geometry from bounds to Polygon

I have a geopandas DataFrame with bounds geometry.

import pandas as pd
import geopandas as gpd

gdf = gpd.GeoDataFrame({
                        'id': [0, 1],
                        'b': [((40.6494140625, -86.7919921875), (40.69335937...)), 
                              ((39.55078125, -93.8232421875), (39.5947265625...))]
                      })

gdf['b'][0]

Bounds(sw=SouthWest(lat=32.8271484375, lon=-96.8115234375), ne=NorthEast(lat=32.87109375, lon=-96.767578125))

print(type(gdf['b'][0]))

<class 'geolib.geohash.Bounds'>

How do I turn Bounds into Polygon geometry type? Like,

Polygon((40.6494140625, -86.7919921875), (40.69335937...))

Suppose you have:-

# bound1 = The geohash.Bounds object.

you can proceed with:-

from shapely.geometry import box
bounds_pgon = box(bounds1.sw.lon, bounds1.sw.lat,
                  bounds1.ne.lon, bounds1.ne.lat)
# Check the result
bounds_pgon.wkt

the output will be similar to this:-

'POLYGON ((-27.9986 70.2987, -27.9986 70.3001, -28.0000 70.3001, -28.0000 70.2987, -27.9986 70.2987))'

This is really the same answer that @swatchi has provided.

Shape of the geometry is defined by the precision of the hash. See reference: geohash

import geolib.geohash
import shapely.geometry
import geopandas as gpd
import pandas as pd

# Bounds(sw=SouthWest(lat=32.8271484375, lon=-96.8115234375), ne=NorthEast(lat=32.87109375, lon=-96.767578125))
# regenerate the referenced geohad bounds
b = geolib.geohash.bounds(
    geolib.geohash.encode(lat=32.8271484375, lon=-96.8115234375, precision=5)
)

print(b)

gdf = gpd.GeoDataFrame(
    pd.DataFrame({"id": [0], "b": [b]}).assign(
        geometry=lambda d: d["b"].apply(
            lambda b: shapely.geometry.box(b.sw.lon, b.sw.lat, b.ne.lon, b.ne.lat)
        )
    ),
    crs="epsg:4326",
)

gdf.explore(height=300, width=300)

output

Bounds(sw=SouthWest(lat=32.8271484375, lon=-96.8115234375), ne=NorthEast(lat=32.87109375, lon=-96.767578125))

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM