📜  geopandas nan to 0 - Python (1)

📅  最后修改于: 2023-12-03 15:00:53.937000             🧑  作者: Mango

Geopandas: Converting NaN to 0 in Python

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.

Step 1: Import Geopandas Library
import geopandas as gpd

Start by importing the geopandas library in your Python code.

Step 2: Load Shapefile
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.

Step 3: Convert NaN to 0
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.

Step 4: Save Changes
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.

Full Code
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')
Conclusion

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.