1

I have numerous XYZ files, which aren't gridded and I'd like to use Python to convert them to shapefiles.

I'm not quite sure how to go about this?

2 Answers 2

4

I have numerous XYZ files, which aren't gridded

from GDAL XYZ – ASCII Gridded XYZ

GDAL supports reading and writing ASCII gridded XYZ raster datasets (i.e. ungridded XYZ, LIDAR XYZ etc. must be opened by other means

The ungridded XYZ file header

# test.xyz
#
0.3517846     -0.7869986      -2.873479    
0.5057634     -0.7079139      -2.871073    
0.6422613     -0.5988617      -2.868600    
.....

Read the xyz file with pandas

import pandas as pd
inputfile = "test.xyz"
df  = pd.read_table(inputfile, skiprows=2, delim_whitespace=True, names=['x', 'y', 'z'])
print(df.head(3))
      x         y         z
0  0.351785 -0.786999 -2.873479
1  0.505763 -0.707914 -2.871073
2  0.642261 -0.598862 -2.868600

Convert the pandas DataFrame to a 2D GeoPandas GeoDataFrame

import geopandas as gpd
gdf2d = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.x, df.y))
print(gdf2d.head(3))
      x         y         z                  geometry
0  0.351785 -0.786999 -2.873479  POINT (0.35178 -0.78700)
1  0.505763 -0.707914 -2.871073  POINT (0.50576 -0.70791)
2  0.642261 -0.598862 -2.868600  POINT (0.64226 -0.59886)
# to shapefile
gdf2d.to_file("test2d.shp")

Convert the pandas DataFrame to a 3D GeoPandas GeoDataFrame

 from shapely.geometry import Point
 gdf3d = gpd.GeoDataFrame(df, geometry=df.apply(lambda row: Point(row.x,row.y,row.z), axis=1))
 print(gdf3d.head(3))
       x         y         z                             geometry
 0  0.351785 -0.786999 -2.873479  POINT Z (0.35178 -0.78700 -2.87348)
 1  0.505763 -0.707914 -2.871073  POINT Z (0.50576 -0.70791 -2.87107)
 2  0.642261 -0.598862 -2.868600  POINT Z (0.64226 -0.59886 -2.86860)
 # to shapefile
 gdf3d.to_file("test3d.shp")
1
  • So interesting, pandas is low case, but GeoPandas is Camel case :)
    – Taras
    Apr 25, 2022 at 11:02
0

I'm not sure but it seems to me that but in Qgis Processing / SAGA, the command 'import feature from XYZ' allows to generate shp

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .