公告:所有在
2025 年 4 月 15 日之前注册使用 Earth Engine 的非商业项目都必须
验证是否符合非商业性质的资格条件,才能继续使用 Earth Engine。
ee.FeatureCollection.iterate
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
将用户提供的函数应用于集合的每个元素。用户提供的函数会获得两个实参:当前元素,以及对 iterate() 的上一次调用返回的值(如果是第一次迭代,则为第一个实参)。结果是用户提供的函数的最终调用所返回的值。
返回 Collection.iterate() 调用的结果。
用法 | 返回 |
---|
FeatureCollection.iterate(algorithm, first) | ComputedObject |
参数 | 类型 | 详细信息 |
---|
此:collection | 集合 | Collection 实例。 |
algorithm | 函数 | 要应用于每个元素的函数。必须接受两个实参:集合的一个元素和上一次迭代的值。 |
first | 对象,可选 | 初始状态。 |
示例
代码编辑器 (JavaScript)
/**
* CAUTION: ee.FeatureCollection.iterate can be less efficient than alternative
* solutions implemented using ee.FeatureCollection.map or by converting feature
* properties to an ee.Array object and using ee.Array.slice and
* ee.Array.arrayAccum methods. Avoid ee.FeatureCollection.iterate if possible.
*/
// Monthly precipitation accumulation for 2020.
var climate = ee.ImageCollection('IDAHO_EPSCOR/TERRACLIMATE')
.filterDate('2020-01-01', '2021-01-01')
.select('pr');
// Region of interest: north central New Mexico, USA.
var roi = ee.Geometry.BBox(-107.19, 35.27, -104.56, 36.83);
// A FeatureCollection of mean monthly precipitation accumulation for the
// region of interest.
var meanPrecipTs = climate.map(function(image) {
var meanPrecip = image.reduceRegion(
{reducer: ee.Reducer.mean(), geometry: roi, scale: 5000});
return ee.Feature(roi, meanPrecip)
.set('system:time_start', image.get('system:time_start'));
});
// A cumulative sum function to apply to each feature in the
// precipitation FeatureCollection. The first input is the current feature and
// the second is a list of features that accumulates at each step of the
// iteration. The function fetches the last feature in the feature list, gets
// the cumulative precipitation sum value from it, and adds it to the current
// feature's precipitation value. The new cumulative precipitation sum is set
// as a property of the current feature, which is appended to the feature list
// that is passed onto the next step of the iteration.
var cumsum = function(currentFeature, featureList) {
featureList = ee.List(featureList);
var previousSum = ee.Feature(featureList.get(-1)).getNumber('pr_cumsum');
var currentVal = ee.Feature(currentFeature).getNumber('pr');
var currentSum = previousSum.add(currentVal);
return featureList.add(currentFeature.set('pr_cumsum', currentSum));
};
// Use "iterate" to cumulatively sum monthly precipitation over the year with
// the above defined "cumsum" function. Note that the feature list used in the
// "cumsum" function is initialized as the "first" variable. It includes a
// temporary feature with the "pr_cumsum" property set to 0; this feature is
// filtered out of the final FeatureCollection.
var first = ee.List([ee.Feature(null, {pr_cumsum: 0, first: true})]);
var precipCumSum =
ee.FeatureCollection(ee.List(meanPrecipTs.iterate(cumsum, first)))
.filter(ee.Filter.notNull(['pr']));
// Inspect the outputs.
print('Note cumulative precipitation ("pr_cumsum") property',
precipCumSum);
print(ui.Chart.feature.byFeature(
precipCumSum, 'system:time_start', ['pr', 'pr_cumsum']));
Python 设置
如需了解 Python API 和如何使用 geemap
进行交互式开发,请参阅
Python 环境页面。
import ee
import geemap.core as geemap
Colab (Python)
import altair as alt
# CAUTION: ee.FeatureCollection.iterate can be less efficient than alternative
# solutions implemented using ee.FeatureCollection.map or by converting feature
# properties to an ee.Array object and using ee.Array.slice and
# ee.Array.arrayAccum methods. Avoid ee.FeatureCollection.iterate if possible.
# Monthly precipitation accumulation for 2020.
climate = (
ee.ImageCollection('IDAHO_EPSCOR/TERRACLIMATE')
.filterDate('2020-01-01', '2021-01-01')
.select('pr')
)
# Region of interest: north central New Mexico, USA.
roi = ee.Geometry.BBox(-107.19, 35.27, -104.56, 36.83)
# A FeatureCollection of mean monthly precipitation accumulation for the
# region of interest.
def mean_precip_ts_fun(image):
mean_precip = image.reduceRegion(
reducer=ee.Reducer.mean(), geometry=roi, scale=5000
)
return ee.Feature(roi, mean_precip).set(
'system:time_start', image.get('system:time_start')
)
mean_precip_ts = climate.map(mean_precip_ts_fun)
# A cumulative sum function to apply to each feature in the
# precipitation FeatureCollection. The first input is the current feature and
# the second is a list of features that accumulates at each step of the
# iteration. The function fetches the last feature in the feature list, gets
# the cumulative precipitation sum value from it, and adds it to the current
# feature's precipitation value. The new cumulative precipitation sum is set
# as a property of the current feature, which is appended to the feature list
# that is passed onto the next step of the iteration.
def cumsum(current_feature, feature_list):
feature_list = ee.List(feature_list)
previous_sum = ee.Feature(feature_list.get(-1)).getNumber('pr_cumsum')
current_val = ee.Feature(current_feature).getNumber('pr')
current_sum = previous_sum.add(current_val)
return feature_list.add(current_feature.set('pr_cumsum', current_sum))
# Use "iterate" to cumulatively sum monthly precipitation over the year with
# the above defined "cumsum" function. Note that the feature list used in the
# "cumsum" function is initialized as the "first" variable. It includes a
# temporary feature with the "pr_cumsum" property set to 0 this feature is
# filtered out of the final FeatureCollection.
first = ee.List([ee.Feature(None, {'pr_cumsum': 0, 'first': True})])
precip_cum_sum = ee.FeatureCollection(
ee.List(mean_precip_ts.iterate(cumsum, first))
).filter(ee.Filter.notNull(['pr']))
precip_cum_sum = precip_cum_sum.map(
lambda feature: feature.set(
'date',
ee.Date(feature.getNumber('system:time_start')).format('YYYY-MM-dd'),
)
)
# Inspect the outputs.
display('Note cumulative precipitation ("pr_cumsum") property', precip_cum_sum)
df = geemap.ee_to_df(precip_cum_sum, ['date', 'pr', 'pr_cumsum'])
display(df)
chart = (
alt.Chart(df)
.mark_line()
.encode(x='date:T', y='pr:Q', color=alt.value('blue'))
)
chart += (
alt.Chart(df)
.mark_line()
.encode(x='date:T', y='pr_cumsum:Q', color=alt.value('red'))
)
chart
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-07-26。
[null,null,["最后更新时间 (UTC):2025-07-26。"],[[["\u003cp\u003e\u003ccode\u003eFeatureCollection.iterate()\u003c/code\u003e applies a custom function iteratively to each element of a FeatureCollection, using the output of the previous iteration as input for the next.\u003c/p\u003e\n"],["\u003cp\u003eIt allows for accumulating or aggregating data across features, enabling operations like cumulative sums or sequential processing.\u003c/p\u003e\n"],["\u003cp\u003eThe user-provided function receives the current element and the previous iteration's result, returning a value used in the next step.\u003c/p\u003e\n"],["\u003cp\u003e\u003ccode\u003eFeatureCollection.iterate()\u003c/code\u003e can be less efficient than \u003ccode\u003emap()\u003c/code\u003e or array-based methods for certain tasks, so consider alternatives if performance is critical.\u003c/p\u003e\n"],["\u003cp\u003eThe final output is the result of the last function call, typically a modified FeatureCollection or a computed value.\u003c/p\u003e\n"]]],[],null,["# ee.FeatureCollection.iterate\n\n\u003cbr /\u003e\n\nApplies a user-supplied function to each element of a collection. The user-supplied function is given two arguments: the current element, and the value returned by the previous call to iterate() or the first argument, for the first iteration. The result is the value returned by the final call to the user-supplied function.\n\n\u003cbr /\u003e\n\nReturns the result of the Collection.iterate() call.\n\n| Usage | Returns |\n|---------------------------------------------------|----------------|\n| FeatureCollection.iterate`(algorithm, `*first*`)` | ComputedObject |\n\n| Argument | Type | Details |\n|--------------------|------------------|-----------------------------------------------------------------------------------------------------------------------------------------|\n| this: `collection` | Collection | The Collection instance. |\n| `algorithm` | Function | The function to apply to each element. Must take two arguments: an element of the collection and the value from the previous iteration. |\n| `first` | Object, optional | The initial state. |\n\nExamples\n--------\n\n### Code Editor (JavaScript)\n\n```javascript\n/**\n * CAUTION: ee.FeatureCollection.iterate can be less efficient than alternative\n * solutions implemented using ee.FeatureCollection.map or by converting feature\n * properties to an ee.Array object and using ee.Array.slice and\n * ee.Array.arrayAccum methods. Avoid ee.FeatureCollection.iterate if possible.\n */\n\n// Monthly precipitation accumulation for 2020.\nvar climate = ee.ImageCollection('IDAHO_EPSCOR/TERRACLIMATE')\n .filterDate('2020-01-01', '2021-01-01')\n .select('pr');\n\n// Region of interest: north central New Mexico, USA.\nvar roi = ee.Geometry.BBox(-107.19, 35.27, -104.56, 36.83);\n\n// A FeatureCollection of mean monthly precipitation accumulation for the\n// region of interest.\nvar meanPrecipTs = climate.map(function(image) {\n var meanPrecip = image.reduceRegion(\n {reducer: ee.Reducer.mean(), geometry: roi, scale: 5000});\n return ee.Feature(roi, meanPrecip)\n .set('system:time_start', image.get('system:time_start'));\n});\n\n// A cumulative sum function to apply to each feature in the\n// precipitation FeatureCollection. The first input is the current feature and\n// the second is a list of features that accumulates at each step of the\n// iteration. The function fetches the last feature in the feature list, gets\n// the cumulative precipitation sum value from it, and adds it to the current\n// feature's precipitation value. The new cumulative precipitation sum is set\n// as a property of the current feature, which is appended to the feature list\n// that is passed onto the next step of the iteration.\nvar cumsum = function(currentFeature, featureList) {\n featureList = ee.List(featureList);\n var previousSum = ee.Feature(featureList.get(-1)).getNumber('pr_cumsum');\n var currentVal = ee.Feature(currentFeature).getNumber('pr');\n var currentSum = previousSum.add(currentVal);\n return featureList.add(currentFeature.set('pr_cumsum', currentSum));\n};\n\n// Use \"iterate\" to cumulatively sum monthly precipitation over the year with\n// the above defined \"cumsum\" function. Note that the feature list used in the\n// \"cumsum\" function is initialized as the \"first\" variable. It includes a\n// temporary feature with the \"pr_cumsum\" property set to 0; this feature is\n// filtered out of the final FeatureCollection.\nvar first = ee.List([ee.Feature(null, {pr_cumsum: 0, first: true})]);\nvar precipCumSum =\n ee.FeatureCollection(ee.List(meanPrecipTs.iterate(cumsum, first)))\n .filter(ee.Filter.notNull(['pr']));\n\n// Inspect the outputs.\nprint('Note cumulative precipitation (\"pr_cumsum\") property',\n precipCumSum);\nprint(ui.Chart.feature.byFeature(\n precipCumSum, 'system:time_start', ['pr', 'pr_cumsum']));\n```\nPython setup\n\nSee the [Python Environment](/earth-engine/guides/python_install) page for information on the Python API and using\n`geemap` for interactive development. \n\n```python\nimport ee\nimport geemap.core as geemap\n```\n\n### Colab (Python)\n\n```python\nimport altair as alt\n\n# CAUTION: ee.FeatureCollection.iterate can be less efficient than alternative\n# solutions implemented using ee.FeatureCollection.map or by converting feature\n# properties to an ee.Array object and using ee.Array.slice and\n# ee.Array.arrayAccum methods. Avoid ee.FeatureCollection.iterate if possible.\n\n# Monthly precipitation accumulation for 2020.\nclimate = (\n ee.ImageCollection('IDAHO_EPSCOR/TERRACLIMATE')\n .filterDate('2020-01-01', '2021-01-01')\n .select('pr')\n)\n\n# Region of interest: north central New Mexico, USA.\nroi = ee.Geometry.BBox(-107.19, 35.27, -104.56, 36.83)\n\n\n# A FeatureCollection of mean monthly precipitation accumulation for the\n# region of interest.\ndef mean_precip_ts_fun(image):\n mean_precip = image.reduceRegion(\n reducer=ee.Reducer.mean(), geometry=roi, scale=5000\n )\n return ee.Feature(roi, mean_precip).set(\n 'system:time_start', image.get('system:time_start')\n )\n\n\nmean_precip_ts = climate.map(mean_precip_ts_fun)\n\n\n# A cumulative sum function to apply to each feature in the\n# precipitation FeatureCollection. The first input is the current feature and\n# the second is a list of features that accumulates at each step of the\n# iteration. The function fetches the last feature in the feature list, gets\n# the cumulative precipitation sum value from it, and adds it to the current\n# feature's precipitation value. The new cumulative precipitation sum is set\n# as a property of the current feature, which is appended to the feature list\n# that is passed onto the next step of the iteration.\ndef cumsum(current_feature, feature_list):\n feature_list = ee.List(feature_list)\n previous_sum = ee.Feature(feature_list.get(-1)).getNumber('pr_cumsum')\n current_val = ee.Feature(current_feature).getNumber('pr')\n current_sum = previous_sum.add(current_val)\n return feature_list.add(current_feature.set('pr_cumsum', current_sum))\n\n\n# Use \"iterate\" to cumulatively sum monthly precipitation over the year with\n# the above defined \"cumsum\" function. Note that the feature list used in the\n# \"cumsum\" function is initialized as the \"first\" variable. It includes a\n# temporary feature with the \"pr_cumsum\" property set to 0 this feature is\n# filtered out of the final FeatureCollection.\nfirst = ee.List([ee.Feature(None, {'pr_cumsum': 0, 'first': True})])\nprecip_cum_sum = ee.FeatureCollection(\n ee.List(mean_precip_ts.iterate(cumsum, first))\n).filter(ee.Filter.notNull(['pr']))\n\nprecip_cum_sum = precip_cum_sum.map(\n lambda feature: feature.set(\n 'date',\n ee.Date(feature.getNumber('system:time_start')).format('YYYY-MM-dd'),\n )\n)\n\n# Inspect the outputs.\ndisplay('Note cumulative precipitation (\"pr_cumsum\") property', precip_cum_sum)\n\ndf = geemap.ee_to_df(precip_cum_sum, ['date', 'pr', 'pr_cumsum'])\ndisplay(df)\n\nchart = (\n alt.Chart(df)\n .mark_line()\n .encode(x='date:T', y='pr:Q', color=alt.value('blue'))\n)\nchart += (\n alt.Chart(df)\n .mark_line()\n .encode(x='date:T', y='pr_cumsum:Q', color=alt.value('red'))\n)\nchart\n```"]]