Creating ee.FeatureCollection from DataFrame in Earth Engine Python

Answered using GPT-4o by GPT4oMini.app

Question:

In Earth Engine python, how to create a ee.FeatureCollection with a number of points, whose coordinates are obtained from a dataframe

Answer:

To create an ee.FeatureCollection in Google Earth Engine (GEE) using Python, where the coordinates of the points are obtained from a pandas DataFrame, you can follow these steps:

  1. Import the necessary libraries.
  2. Initialize the Earth Engine API.
  3. Create a pandas DataFrame with your coordinates.
  4. Convert the DataFrame to a list of ee.Feature objects.
  5. Create an ee.FeatureCollection from the list of ee.Feature objects.

Here's a step-by-step example:

import ee
import pandas as pd

# Initialize the Earth Engine API
ee.Initialize()

# Example DataFrame with coordinates
data = {
    'latitude': [37.7749, 34.0522, 40.7128],
    'longitude': [-122.4194, -118.2437, -74.0060],
    'name': ['San Francisco', 'Los Angeles', 'New York']
}
df = pd.DataFrame(data)

# Function to convert a row of the DataFrame to an ee.Feature
def row_to_feature(row):
    point = ee.Geometry.Point([row['longitude'], row['latitude']])
    return ee.Feature(point, {'name': row['name']})

# Convert the DataFrame to a list of ee.Feature objects
features = df.apply(row_to_feature, axis=1).tolist()

# Create an ee.FeatureCollection from the list of ee.Feature objects
feature_collection = ee.FeatureCollection(features)

# Print the FeatureCollection to verify
print(feature_collection.getInfo())

Explanation:

  1. Import Libraries: Import the ee module for Earth Engine and pandas for handling the DataFrame.
  2. Initialize Earth Engine: Call ee.Initialize() to initialize the Earth Engine API.
  3. Create DataFrame: Create a pandas DataFrame with your coordinates and any additional properties you want to include.
  4. Convert Rows to Features: Define a function row_to_feature that takes a row of the DataFrame and converts it to an ee.Feature with a Point geometry and properties.
  5. Apply Function: Use the apply method to apply the row_to_feature function to each row of the DataFrame, converting it to a list of ee.Feature objects.
  6. Create FeatureCollection: Use ee.FeatureCollection to create a FeatureCollection from the list of ee.Feature objects.
  7. Print FeatureCollection: Optionally, print the FeatureCollection to verify its contents.

This code will create an ee.FeatureCollection with points corresponding to the coordinates in the DataFrame, and each point will have properties as specified in the DataFrame.