1

I am calculating ndvi means for each raster in a set of before and after change detection images using rasterio. The code below works but I am getting more than 80% NaN values in either the before or after raster mean ndvi due to cloud masking. How can I edit the code to reduce the number of NaN values while computing ndvi mean values?

%matplotlib inline

import numpy as np
import rasterio
from rasterio.plot import show
bf = []
af = []
dates =[]
swarmpoints_path = 'Laikipia_Shrubland_2020'
## loop though the dir
for file in os.listdir(swarmpoints_path):
    # if before is in the file name, then extract mean and add to the list
    if 'before' in file:
        path = os.path.join(swarmpoints_path, file)
        print(path)
        before0 = rasterio.open(path)
        bf_ndvi = before0.read([14])
        bf_mean = bf_ndvi.mean()
        print(bf_mean)
        print(type(bf_mean))
        bf.append(bf_mean)
        date = file.split('_')[-1].split('.')[0]
        dates.append(date)
    # if after is in the file name, extract mean and add to list
    if 'after' in file:
        path = os.path.join(swarmpoints_path, file)
        print(path)
        after0 = rasterio.open(path)
        af_ndvi = after0.read([14])
        af_mean = af_ndvi.mean()
        af.append(af_mean)
        print(af_mean)
    else:
        print( file + ' ' + 'skipped')

        
        
#create a dataframe from lists of mean
import pandas as pd  
# create columns bf_mean, af_mean
data ={'bf_mean':bf, 'af_mean':af}
# create df
df = pd.DataFrame(data, index = dates)
df
2
  • numpy.nanmean perhaps?
    – user2856
    Commented Oct 15, 2021 at 3:31
  • @user2856 thanks a lot it worked for me. Applying the mean on either axis 1 or 0 introduces the NaN so I will use the default setting. Thanks again!
    – Shiraz
    Commented Oct 15, 2021 at 9:37

0

Your Answer

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

Browse other questions tagged or ask your own question.