Google Earth Engine Python – Adding a New Column to FeatureCollection in GEE

feature-collectiongoogle-earth-enginepointpython

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()

Best Answer

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()
Related Question