Skip to content

Instantly share code, notes, and snippets.

@bennyistanto
Created June 19, 2020 07:10
Show Gist options
  • Save bennyistanto/62db83a429887f2c97739b0557f3b89b to your computer and use it in GitHub Desktop.
Save bennyistanto/62db83a429887f2c97739b0557f3b89b to your computer and use it in GitHub Desktop.
Extract percentile from each cell based on raster timeseries
Before running script, adjust below:
1. Line 14 - input directory
2. Line 15 - output directory
2. Line 30 - name input array and k value (n_80 and 80.)
3. line 33 - {in_array},{lower_left_corner},{x_cell_size},{y_cell_size},{value_to_nodata}
4. line 35 - same as above
5. line 36 - output name
#!/usr/bin/python
# -*- coding: utf8 -*-
import arcpy
import numpy
import sys
#Overwrite the output if exist
arcpy.env.overwriteOutput = True
reload(sys)
sys.setdefaultencoding('utf8')
# Adjust folder directory
infolder = r"Z:\Temp\CHIRPS\Daily\Max2"
outfolder = r"Z:\Temp\CHIRPS\Daily\Pct2"
arcpy.env.workspace = infolder
rasters = arcpy.ListRasters()
nmpyrys = []
for i in rasters:
nmpyrys.append(arcpy.RasterToNumPyArray(i))
a = numpy.array(nmpyrys)
nmpyrys_m = []
for i in nmpyrys:
m = numpy.where(a[0] == 0, 1, 0)
am = numpy.ma.MaskedArray(i, mask=m)
nmpyrys_m.append(am)
a_m = numpy.array(nmpyrys_m)
n_80 = numpy.nanpercentile(a_m, 80., axis=0)
# Based on lower-left and pixel size global CHIRPS data
arcpy.NumPyArrayToRaster(n_80, arcpy.Point(-180.0000000,-50.0000015), 0.050000000745058, 0.050000000745058, 0)
out = arcpy.NumPyArrayToRaster(n_80, arcpy.Point(-180.0000000,-50.0000015), x_cell_size=0.050000000745058, y_cell_size=0.050000000745058, value_to_nodata=0)
out_name = "\\".join([outfolder, "n_80.tif"])
out.save(out_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment