3

I am trying to convert some code snippets from GEE JavaScript to Python. This code computes the monthly averages of NDVI images given a range of years and a range of months.

This is my code in JavaScript:

var years = ee.List.sequence(2013, 2021);
var sowingMonths = ee.List.sequence(10, 12);
var growingMonths = ee.List.sequence(1, 4);

monthly_Sowing_Avg = function (Collection){
 return ee.ImageCollection.fromImages(
   years.map(function(year) {
     return sowingMonths.map(function(month) {
       return Collection
       .filter(ee.Filter.calendarRange(year, year, 'year'))
       .filter(ee.Filter.calendarRange(month, month, 'month'))
       .mean()
       .set({'month': month, 'year': year});
 });
}).flatten())}

and this is what I tried to do in Python:

years = ee.List.sequence(2013, 2021)
sowingMonths = ee.List.sequence(10, 12)
growingMonths = ee.List.sequence(1, 4)
def monthly_Sowing_Avg (collection, years, months):

 def mapOverMonths (month):
   return  sowCol.filter(ee.Filter.calendarRange(year, year, 'year')) \
                 .filter(ee.Filter.calendarRange(month, month, 'month')) \
                 .mean() \
                 .set({'month': month, 'year': year})

 def mapOverYears (year):
   return Months.map(mapOverMonths)

 return ee.ImageCollection.fromImages(years.map(mapOverYears))

Is the Python version correct or not?

1 Answer 1

0

I solved it using this (not very optimized solution):

def monthly_Avg (collection, years, months):
  avg = []
  for year in years:
    for month in months:
      Monthly_avg = collection.filter(ee.Filter.calendarRange(year, year, 'year')) \
                              .filter(ee.Filter.calendarRange(month, month, 'month')) \
                              .mean() \
                              .set({'month': month, 'year': year})
      avg.append (Monthly_avg)
  return ee.ImageCollection.fromImages(avg)

## Compute monthly averages for both seasons
monthly_sowing_Avg = monthly_Avg (ndvi_sowSeason, years, sowingMonths)
monthly_growing_Avg = monthly_Avg (ndvi_growSeason, years, growingMonths)

years, sowingMonths, and growingMonths are lists.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.