python - 有没有办法将 numpy.where() 用于将 NaN 值作为无数据的栅格数据?
问题描述
我有一个栅格数据,其中包含 NaN 值作为无数据。我想从中计算新的栅格,例如 if raster==0 do statement1,if raster==1 do statement2,如果 raster 介于 0 和 1 之间,则 do statement3,否则不要更改值。如何使用 numpy.where() 函数来做到这一点?
这是我的代码:
import os
import rasterio
from rasterio import plot
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
os.listdir('../NDVI_output')
ndvi1 = rasterio.open("../NDVI_output/NDVI.tiff")
min_value = ndvi_s = np.nanmin(ndvi) #NDVI of Bare soil
max_value = ndvi_v = np.nanmax(ndvi) #NDVI of full vegetation cover
fvc = (ndvi-ndvi_s)/(ndvi_v-ndvi_s) #fvc: Fractional Vegetation Cover
band4 = rasterio.open('../TOAreflectance_output/TOAref_B4.tiff')
toaRef_red = band4.read(1).astype('float64')
emiss = np.where((fvc == 1.).any(), 0.99,
(np.where((fvc == 0.).any(), 0.979-0.046*toaRef_red,
(np.where((0.<fvc<1.).any(), 0.971*(1-fvc)+0.987*fvc, fvc)))))
解决方案
如果raster
是一个数组,
raster == x
给出一个布尔掩码,其形状与 相同raster
,指示 的哪些元素(在您的情况下为像素)raster
等于x
np.where(arr)
arr
给出计算结果为 true的数组元素的索引.np.where(raster == x)
, 因此, 给出像素的索引raster
等于x
.np.any(arr)
当且仅当 的至少一个元素的arr
计算结果为 true 时才返回 True。np.any(raster == x)
,因此,告诉您是否至少有一个像素raster
是 x。
假设fvc
和toaRef_red
具有相同的形状并且您想创建一个新emiss
的发射数组,如果fvc
为 1,则将其设置为 0.99,0.979 - 0.046 * toaRef_red
如果fvc
为 0,0.971 * (1 - fvc) + 0.987 * fvc
如果 0 < fvc
< 1,否则为 NaN,您可以执行以下操作:
emiss = np.full(ndvi.shape, np.nan) # create new array filled with nan
emiss[fvc == 1] = 0.99
mask = fvc == 0
emiss[mask] = 0.979 - 0.046 * toaRef_red[mask]
mask = (fvc > 0) & (fvc < 1)
emiss[mask] = 0.971 * (1 - fvc[mask]) + 0.987 * fvc[mask]
这与以下内容相同:
emiss = np.full(ndvi.shape, np.nan) # create new array filled with nan
emiss[np.where(fvc == 1)] = 0.99
idx = np.where(fvc == 0)
emiss[idx] = 0.979 - 0.046 * toaRef_red[idx]
idx = np.where((fvc > 0) & (fvc < 1))
emiss[idx] = 0.971 * (1 - fvc[idx]) + 0.987 * fvc[idx]
后者显然是多余的。你不需要np.where
这里。
推荐阅读
- python - 将文本文件中的重复数字打印到不同的文件-python?
- r - R中的gstat - 变异函数截止距离不适用于大型网格数据集的较大指定距离
- excel - 在 Excel 中运行报表后没有可视内容
- php - 在数据库中存储数组
- c# - 在 Xamarin 和 MVVM 中绑定 ObservableCollection Listview 时不刷新特定标签
- javascript - 边框底部的 CSS 转换延迟
- reporting-services - #SSRS输出中的计算值错误
- angularjs - 通过 MEAN 架构上的 Datatable 配置搜索字段
- javascript - 如何在 React 中的现有 DOM 中追加或插入 HTML 元素
- sql - sql teradata 过滤日期 - 数据库版本 Teradata 15.10.06.02 和提供程序版本 Teradata.Net 15.11.0.0