.loc return 是一个 Pandas 系列,而不是 GeoDataFrame。如何 return GeoDataFrame

.loc returns a Pandas Series, not a GeoDataFrame. How to return a GeoDataFrame

我有一个GeoDataFrame这样的

import pandas as pd
import geopandas

df = pd.DataFrame(
    {'City': ['Buenos Aires', 'Brasilia', 'Santiago', 'Bogota', 'Caracas'],
     'Country': ['Argentina', 'Brazil', 'Chile', 'Colombia', 'Venezuela'],
     'Latitude': [-34.58, -15.78, -33.45, 4.60, 10.48],
     'Longitude': [-58.66, -47.91, -70.66, -74.08, -66.86]})

gdf = geopandas.GeoDataFrame(
    df, geometry=geopandas.points_from_xy(df.Longitude, df.Latitude))

gdf.set_index("City", inplace = True)

现在我想要数据的一个子集。我这样做

gdf.loc["Santiago"]

然而,这 return 是

type(gdf.loc["Santiago"])

<class 'pandas.core.series.Series'>

我想要 GeoDataFrame 作为 return / 将 pandas.core.series.Series 转换为 GeoDataFrame。我该怎么做?

根据这个answer,这就可以了。

gdf.loc[["Santiago"]]
type(gdf.loc[["Santiago"]])

<class 'geopandas.geodataframe.GeoDataFrame'>

gdf.loc["Santiago"]

输出

Country                      Chile
Latitude                    -33.45
Longitude                   -70.66
geometry     POINT (-70.66 -33.45)
Name: Santiago, dtype: object

这是一个系列,国家、纬度和经度不是几何图形。因此它必须是 Series 来表示 GeoDataFrame

中的行

仅找到几何图形:

type(gdf.loc["Santiago", "geometry"])

输出

shapely.geometry.point.Point

是一个单独的几何图形(不是 SeriesGeoSeries),因为它唯一标识了一个值。