I'm new in coding. I have a shapefile (points) and 15 raster files My purpose is get the values from all raster to point (each point will get value from 2 or 3 nearest cell baseed on distance of the point to cell). I already built code for that and it is working but it takes so much time for running.

Could you optimize the code to make it run faster?

import os
import rioxarray as rxr
import geopandas as gpd
import numpy as np

### definition extract_raster:
def extract_raster(points_gdf, raster_xarray):
    extracted_values = []
    for _, point in points_gdf.iterrows():
        value = raster_xarray.interp(x=point.geometry.x, y=point.geometry.y)
    column_name = 'raw'
    points_gdf[column_name] = extracted_values
    points_gdf[column_name] = points_gdf[column_name].astype(float)
    return points_gdf
# import data

lidar_chm_path = os.path.join(r"D:\CHM\CHM.tif")
lidar_chm_xr = rxr.open_rasterio(lidar_chm_path, masked=True).squeeze()
NFI_path = os.path.join("SHP_file", "Final_NFI.shp")
NFI_data = gpd.read_file(NFI_path)

extract_raster(NFI_data, lidar_chm_xr)
NFI_data.rename(columns={'raw': 'CHM'}, inplace=True)
  • 1
    How many points are there?
    – BERA
    Aug 24, 2023 at 9:23
  • 1
    Also how large are your raster files? The dimension and resolution of the rasters.
    – Padmanabha
    Aug 24, 2023 at 13:43
  • For code review there is the Code Review Stack Exchange.
    – PolyGeo
    Aug 24, 2023 at 19:13
  • I have around 4000 points. The raster size = 20810x18620 pixel, with resolution = 30x30m. Aug 25, 2023 at 6:55


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.