📅  最后修改于: 2023-12-03 15:00:53.937000             🧑  作者: Mango
Geopandas is an open-source library that allows you to work with geospatial data in Python. One common task when working with data is to replace missing values. In this article, we will show you how to convert NaN values to 0 using Geopandas in Python.
import geopandas as gpd
Start by importing the geopandas
library in your Python code.
gdf = gpd.read_file('data/shapefile.shp')
Load the shapefile into a GeoDataFrame using the geopandas.read_file()
function. Replace data/shapefile.shp
with the path to your shapefile.
gdf.fillna(0, inplace=True)
Replace all NaN values with 0 in the GeoDataFrame using the fillna()
method. Setting inplace=True
ensures that the changes are made to the original GeoDataFrame.
gdf.to_file('data/shapefile_nan_to_0.shp')
Once you have replaced all NaN values with 0, you can save the modified GeoDataFrame to a new shapefile using the to_file()
method. Replace data/shapefile_nan_to_0.shp
with the path and filename for your new shapefile.
import geopandas as gpd
# Load shapefile
gdf = gpd.read_file('data/shapefile.shp')
# Convert NaN to 0
gdf.fillna(0, inplace=True)
# Save changes
gdf.to_file('data/shapefile_nan_to_0.shp')
In this article, you learned how to convert NaN values to 0 using Geopandas in Python. This method is useful if you want to replace missing values in your geospatial dataset. You can now use the modified GeoDataFrame to create visualizations or analyze your geospatial data.