geopandas.geodataframe.GeoDataFrame 的中心

问题描述 投票:0回答:1

下面的代码呈现了旧金山县人口普查区的地图。请注意,它对地图的中心进行了硬编码:

import plotly.express as px
import censusdis.data as ced
from censusdis.datasets import ACS5

variable = 'B01001_001E' 

df = ced.download(
    dataset=ACS5,
    vintage=2022,         
    download_variables=['NAME', variable], 
    state='06',
    county='075',
    tract='*',
    with_geometry=True)

df = df.set_index('NAME')
df = df.dropna()

fig = px.choropleth_mapbox(df, 
                           geojson=df.geometry,
                           locations=df.index, 
                           center={'lat': 37.74180915, 'lon': -122.38474831884692}, 
                           color=variable, 
                           color_continuous_scale="Viridis", 
                           mapbox_style="carto-positron", 
                           opacity=0.5,
                           zoom=10)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()

我想以编程方式为该国每个县创建这样的地图。然而,要做到这一点,我需要能够导出

df
的中心(它是
geopandas.geodataframe.GeoDataFrame
类型的对象)。我不确定该怎么做。

我知道该类有一个成员变量

.centroid
。但当我调用它时:

  • 它返回一个
    geopandas.geoseries.GeoSeries
    类型的对象,它似乎是每个 Tract 的中心。但我需要所有区域都有一个中心点。
  • 它给了我警告
    Geometry is in a geographic CRS. Results from 'centroid' are likely incorrect. Use 'GeoSeries.to_crs()' to re-project geometries to a projected CRS before this operation.
    所以即使我解决了第一点,看来我仍然需要做一个额外的步骤。

如何获取县内所有地块的中心?

geopandas
1个回答
0
投票

您似乎正在寻找geopandas.total_bounds。该函数返回整个 GeoDataFrame 的最小边界框。

要获得它的中心,您可以使用 shapely。例如。像这样的东西:

import geopandas as gpd
import shapely

p1 = shapely.Polygon([[0, 0], [0, 1], [1, 1], [0, 0]])
p2 = shapely.Polygon([[99, 99], [99, 100], [100, 100], [99, 99]])
df = gpd.GeoDataFrame(data={"desc": ["p1", "p2"]}, geometry=[p1, p2])

center = shapely.box(*df.total_bounds).centroid
print(center)
# POINT (50 50)
© www.soinside.com 2019 - 2024. All rights reserved.