2

I want to add random values to a new property column landcover in the feature collection, but it only yields one value for all feature/points. It should be random values for each feature. Here is my code

import ee
import random
points=ee.FeatureCollection("users/miketu72/2021_LD_test_point")
# Add a column named landcover with random values from 1 to 4
def landcover(feat):
    code=list("1234")
    num=random.choice(code)
    newfeat=feat.set("landcover",ee.Number(int(num)))
    return newfeat
newPoints=points.map(landcover)
newPoints.getInfo()
2
  • Client side functions are only called once, so every image is getting the same random number. Use collection.randomColumn(). See developers.google.com/earth-engine/guides/client_server for more about client vs. server. Commented Mar 28, 2022 at 10:55
  • Thanks Noel. I think I have to modify it using Python way and then make featurecollection again.
    – Tuyen
    Commented Mar 28, 2022 at 16:00

1 Answer 1

1

Like Noel said, use randomColumn():

# Create some features for testing
points = ee.FeatureCollection([
    ee.Feature(None, {'i': i})
    for i in range(0, 10)
])

new_points = points \
    .randomColumn('landcover') \
    # Turn landcover from a float between 0 and 1 to int between 1 and 4
    .map(lambda feature: 
         feature.set(
             'landcover', 
             feature.getNumber('landcover').multiply(4).ceil()
         )
    )

new_points.getInfo()

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.