How to convert a xarray DataArray to a geopandas GeoDataFrame

Viewed 1623

In xarray there is a method called to_dataframe(), see:

http://xarray.pydata.org/en/stable/pandas.html

With this method a DataArray can be converted to a pandas DataFrame.

How can I convert a convert a xarray DataArray to a geopandas GeoDataFrame, so like the above but with polygons included of the gridcells?

1 Answers

This code will create a GDF with a geometry column containing a series of POINT objects corresponding to the lat/lon coordinates in my xarray.

import geopandas as gpd
import xarray as xr

xds = xr.open_dataset('yourfile.nc')
xarr = x['value_column']
df = xarr.to_dataframe().reset_index()

gdf = gpd.GeoDataFrame(
    df.value_column, geometry=gpd.points_from_xy(df.lon,df.lat))
Related