Python netcdf - 将指定值转换为NaN

时间:2016-07-26 11:39:18

标签: python python-2.7 nan netcdf

我正在绘制来自卫星和天气模型的风数据的pcolourmesh。这些值都存储在netcdf文件中。下面我尝试用NaN替换等于70或0的值,这不会给出错误,但它也不会创建NaN,nozeros与原始数据集的大小相同。我查看了数据,它确实有值== 70和0。

 import netCDF4 as nc
import numpy as np
import matplotlib.pyplot as plt
import csv as cs
import pandas as pd

ncfile = nc.Dataset('C:\Users\mmso2\Google Drive\ENVI_I-PAC_2007_10_21_21_22_47.nc')
SARwind = ncfile.variables['sar_wind']
ModelWind = ncfile.variables['model_speed']
LON = ncfile.variables['longitude']
LAT = ncfile.variables['latitude']
LandMask = ncfile.variables['mask']

    #clean the data of values = 70
    SARwind_nan = SARwind

    for i in SARwind_nan:
        if i.any() == 70:
            i = np.nan
        elif i.any()==0:
            i = np.nan 

  nozeros=np.count_nonzero(~np.isnan(SARwind_nan))

另外,我想将LandMask> = 0的区域转换为NaN,有更好的方法吗?

由于

1 个答案:

答案 0 :(得分:1)

您的代码中存在多个问题,请忽略缩进语法错误。

以下代码无效。什么是i?结果未保存。

for i in SARwind_nan:
        if i.any() == 70:
            i = np.nan
            ...

这是一个应该做你想做的事的例子。

SARwind = np.array([
  [1,2,0,-4,-5],
  [6,0,70,-9,-15],
  [10,11,-12,70,-14],
  [0,17,70,-19,-20],
  ], dtype=np.float32)

SARwind_nan =  SARwind.copy()
SARwind_nan[SARwind_nan == 0.0] = np.nan
SARwind_nan[SARwind_nan == 70.0] = np.nan

print SARwind_nan

nozeros=np.count_nonzero(~np.isnan(SARwind_nan))
print nozeros