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

Time:11-02

I have a GeoDataFrame like this

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)

Now I want to have a subset of the Data. I do this by

gdf.loc["Santiago"]

However, this returns a

type(gdf.loc["Santiago"])

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

I want a GeoDataFrame as a return / Convert pandas.core.series.Series into a GeoDataFrame. How would I do that?

CodePudding user response:

According to this answer, this will do the trick.

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

<class 'geopandas.geodataframe.GeoDataFrame'>

CodePudding user response:

gdf.loc["Santiago"]

output

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

This is a series, Country, Latitude & Longitude are not geometry. Hence it has to be a Series to represent the row from the GeoDataFrame

Locate just the geometry:

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

output

shapely.geometry.point.Point

Is an individual geometry (not a Series or GeoSeries) as expected as it uniquely identifies a value.

  • Related