I have a shapefile with a column (named "Type") that lists 10 different land use types (string). I am trying to export each specific land use type as a distinct shapefile so that I will have 10 shapefiles each of which containing data on one land use. I have written the code below, but it only exports one land use (the one that comes last alphabetically), and I am not able to figure out how to fix my code.
data = gpd.read_file('G:/My Drive/The effects of land use/Final_Land_Use_-_2015.shp')
use = data.Type.unique()
for Type in use:
gdf = data[data.Type==Type]
gdf.to_file("Desktop/LST/{Type}.shp")
CodePudding user response:
The problem you have is that you're not properly constructing the file path. You're trying to use python's string formatting, but you didn't use the "f" prefix.
data = gpd.read_file('G:/My Drive/The effects of land use/Final_Land_Use_-_2015.shp')
land_uses = data["Type"].unique()
for land_use in land_uses:
gdf = data.loc[data["Type"] == land_use]
gdf.to_file(f"Desktop/LST/{land_uses}.shp") # <-- see the f-prefix?
CodePudding user response:
Modified: I completely missed deleted the data filtering part in my earlier post , Hope this works for you (may not be the most the efficient code, could be more simplified). I assumed the land-use column is string type Note: i think its always best to write the spatial files in the different folder
import geopandas as gpd
file_path="G:/My Drive/The effects of land use/Final_Land_Use_-_2015.shp"
data= gpd.read(file_path)
extnsion='.shp'
use = data.Type.unique()
for test in use:
gdf = data[data.Type==test]
a = file_path test extnsion
gdf.to_file(a)