Search code examples
pythonrrasterarcgisqgis

When averaging rasters, is there a way to calculate the n number of non-NaN values per pixel used to calculate the pixel means?


I have about 40 rasters (tiffs). I averaged the rasters, which is straightforward. As a second output however I would like to determine the n number of non-NaN values per pixel used to calculate each pixel mean, and display this as a raster. Basically, I need to know for each pixel how many values were used to calculate the mean. Is this possible? I am looking for solutions either with GIS (either ArcGIS or QGIS is fine), Python or R. Cheers.


Solution

  • Here is how you can do that with R using the terra package

    library(terra)
    s <- rast(system.file("ex/logo.tif", package="terra"))   
    
    m <- mean(s)
    n <- sum(!is.na(s))
    

    Or the raster package

    library(raster)
    b <- brick(system.file("external/rlogo.grd", package="raster"))
    mb <- mean(b)
    nb <- sum(!is.na(b))