I'm writing out a way to calculate the Enhanced Vegetation Index (EVI) of Sentinel-2 images in the Python API of Google Earth Engine, specifically in Jupyter Notebook. I have the same code written for the JavaScript API, but am trying to make it for Python because I read in Exporting Large Number of Landsat Images from Google Earth Engine that it's better for batch exporting. To calculate the EVI, I've written out a function, but keep getting an error message. My Python code is

!pip install earthengine-api
import ee

#evi calculation
def addEVI(EVI = image.expression((image.select('B8')), (image.select('B4'), (image.select('B2')) 
return (2.5 * (((image.select('B8').divide(10000)) - (image.select('B4').divide(10000))) / ((image.select('B8').divide(10000)) + 6 * (image.select('B4').divide(10000)) - 7.5 * (image.select('B2').divide(10000))) + 1)).image.addBands(EVI)

Which returns the error:

File "<ipython-input-51-eeccb7cd2d65>", line 4
    return (2.5 * (((image.select('B8').divide(10000)) - (image.select('B4').divide(10000))) /
SyntaxError: invalid syntax

I've been following the syntax guide from the Google Earth Engine Python Installation Guide. My JavaScript code for this same EVI calculation is:

// make EVI expression into a function
var addEVI=function(image){
var EVI = image.expression(
      '2.5 * ((NIR - RED) / (NIR + 6 * RED - 7.5 * BLUE + 1))', {
      'NIR' : image.select('B8').divide(10000),
      'RED' : image.select('B4').divide(10000),
      'BLUE': image.select('B2').divide(10000)}).rename('EVI');
      return image.addBands(EVI);

What about my Python code has invalid syntax?


1 Answer 1


Here is the Python equivalent of your function:

def addEVI(image):
    EVI = image.expression('2.5 * ((NIR - RED) / (NIR + 6 * RED - 7.5 * BLUE + 1))', {
        'NIR' : image.select('B8').divide(10000),
        'RED' : image.select('B4').divide(10000),
        'BLUE': image.select('B2').divide(10000)}).rename('EVI')
    return image.addBands(EVI)
  • @Beck I deleted my answer as Kadir has rewritten your JS to Python (presumably working). However, I will tell your that the problem with your syntax in your posted code, is that your return is outside the scope of your function, you need to indent it because Python is whitespace sensitive. Also, take note of the cleanliness of Kadir's code, it is easy to read; one-liners are can be clever but maintenance can be a nightmare; you'll thank yourself in the future.
    – RomaH
    Dec 30, 2021 at 1:46

Your Answer

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