Google Earth Engine中替换FeatureCollection字符串值为数字的报错问题
问题:Google Earth Engine字符串转数值报错解决
我有一个包含Dominance列的FeatureCollection,该列将区域按利益相关者主导类型分类,值为字符串类型的'Small'、'Medium'、'Large'和'Others'。我想把这些字符串分别替换为1、2、3、4,使用了以下代码:
var Shape = ee.FeatureCollection('XYZ') var Shape_custom = Shape.select(['Dominance']) var conditional = function(feat) { return ee.Algorithms.If(feat.get('Dominance').eq('Small'), feat.set({class: 1}), feat) } var test = Shape_custom.map(conditional) // 原本计划重复这个逻辑处理所有分类
运行后报错:feat.get(...).eq is not a function,请问哪里操作错误?
错误原因
feat.get('Dominance')返回的是原生JavaScript字符串,不是Google Earth Engine的ee.String对象,而.eq()是EE专属对象的方法,原生JS字符串没有这个方法,所以会报错。
修复方案
方案1:包装为EE字符串后使用多层条件判断
先把获取到的字段值用ee.String()包装,再调用.eq()做判断,同时用嵌套的ee.Algorithms.If一次性处理所有分类:
var Shape = ee.FeatureCollection('XYZ') var Shape_custom = Shape.select(['Dominance']) var conditional = function(feat) { var dominance = ee.String(feat.get('Dominance')); // 嵌套判断所有分类,匹配不到的默认设为4(对应Others) var newClass = ee.Algorithms.If(dominance.eq('Small'), 1, ee.Algorithms.If(dominance.eq('Medium'), 2, ee.Algorithms.If(dominance.eq('Large'), 3, 4))); return feat.set({class: newClass}); } var test = Shape_custom.map(conditional)
方案2:使用remap()方法(更推荐)
利用EE的remap方法直接完成字符串到数值的映射,代码更简洁易维护:
var Shape = ee.FeatureCollection('XYZ') var Shape_custom = Shape.select(['Dominance']) // 定义原始分类列表和对应的目标数值 var fromCategories = ['Small', 'Medium', 'Large', 'Others']; var toValues = [1, 2, 3, 4]; var test = Shape_custom.map(function(feat) { // 将字符串字段转为EE字符串后调用remap var classValue = ee.String(feat.get('Dominance')).remap(fromCategories, toValues); return feat.set({class: classValue}); });
内容的提问来源于stack exchange,提问作者Ep1c1aN
相关产品推荐
相关产品推荐

