How to convert from Javascript to Python API for FeatureCollection in GEE?

918 views Asked by At

I have a JS Code which runs well:

dataset = ee.Image('USGS/SRTMGL1_003');
elevation = dataset.select('elevation');

var means_of_tea = tea.map(function(field){
  var elevation_mean = elevation.reduceRegion({
    reducer: ee.Reducer.mean(),
    geometry: field.geometry(),
    scale: 30,
    maxPixels: 1e9
  });
  var slope_mean = slope.reduceRegion({
    reducer: ee.Reducer.mean(),
    geometry: field.geometry(),
    scale: 30,
    maxPixels: 1e9
  });
  return field.set({elevation:elevation_mean, slope:slope_mean});

I tried to convert the code to python:

def map_fc(field):
  elevation_mean = elevation.reduceRegion({
      'reducer': ee.Reducer.mean(),
      'geometry': field.geometry(),
      'scale': 30,
      'maxPixels': 1e9
  })
  return field.set({'elevation': elevation_mean})
teawithmean = tea.map(map_fc)

But gives the error:

<ipython-input-36-e999072d4723> in <module>()
      9   })
     10   return field.set({'elevation': elevation_mean})
---> 11 teawithmean = tea.map(inmap)

17 frames
/usr/local/lib/python3.6/dist-packages/ee/__init__.py in init(self, *args)
    397           raise EEException(
    398               'Invalid argument for ee.{0}(): {1}.  '
--> 399               'Must be a ComputedObject.'.format(name, args))
    400         else:
    401           result = args[0]

EEException: Invalid argument for ee.Reducer(): ({'reducer': <ee.Reducer object at 0x7f3b4699e4a8>, 'geometry': ee.Geometry({
  "functionInvocationValue": {
    "functionName": "Feature.geometry",
    "arguments": {
      "feature": {
        "argumentReference": null
      }
    }
  }
}), 'scale': 30, 'maxPixels': 1000000000.0},).  Must be a ComputedObject.

I've read the google guide for converting form JS to python but had no idea why this happen. Is the error duo to wrong syntax?

1

There are 1 answers

3
Kevin Reid On BEST ANSWER

In the Python EE API, use Python named argument syntax instead of dictionaries for arguments.

  elevation_mean = elevation.reduceRegion(
      reducer=ee.Reducer.mean(),
      geometry=field.geometry(),
      scale=30,
      maxPixels=1e9
  )

Note that a property name is not a named argument, so set() works the same way as in JavaScript; you can use a dictionary or not, but do not use =.

return field.set({'elevation': elevation_mean})
# or
return field.set('elevation', elevation_mean)