Python - 如何平滑 xarray 图?

ste*_*eve 1 python smoothing python-xarray

我有一些 NetCDF 文件,我需要从中绘制一些变量。我使用以下小代码来绘制我需要的数据:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
%matplotlib inline
import xarray as xr
os.chdir
fname = "/home/data.nc"
ds = xr.open_dataset(fname)
ds['Evap_obs'].plot()
plt.show()
Run Code Online (Sandbox Code Playgroud)

其工作正常并产生下图:

在此输入图像描述

我现在的问题是这个情节不太可读。因此我希望事先平滑数据。为此我有这个小功能:

def mov_avg(x,window,min_count=None,axis=-1):
    import bottleneck as bn 
    yy=np.ma.filled(np.ma.fix_invalid(x),np.nan)
    yyF=np.ma.masked_all(yy.shape)
    xtmp=bn.move_mean(yy,window,min_count=min_count,axis=axis)
    wd1=(window-1)/2
    ndim = len(yy.shape)
   #print xtmp.shape,ndim,axis,window,wd1
    if ndim ==1 :
   #print wd1,-wd1,wd-1
        yyF[wd1:-wd1]=np.ma.fix_invalid(xtmp[window-1:])

    elif ndim == 2:
        if axis==-1 or axis==1:
            yyF[:,wd1:-wd1]=np.ma.fix_invalid(xtmp[:,window-1:])
        elif axis==0:
            yyF[wd1:-wd1,:]=np.ma.fix_invalid(xtmp[window-1:,:])

    return yyF
Run Code Online (Sandbox Code Playgroud)

然后,当我希望对我的数据运行此函数以使其平滑时,如下所示(使用 7 个时间步长的窗口进行平滑):

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
%matplotlib inline
import xarray as xr
os.chdir
fname = "/home/data.nc"
ds = xr.open_dataset(fname)
obs = ds['Evap_obs']
obs = mov_avg(obs,7)
obs.plot()
Run Code Online (Sandbox Code Playgroud)

它不起作用,我收到以下 ValueError:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-18-6a8a2dd438c6> in <module>()
      7 #dsloc = ds.sel(lon=230.5,lat=55.0,method='nearest')
      8 obs = ds['Evap_obs']
----> 9 obs = mov_avg(obs,7)
     10 obs.plot()
     11 #ds['Evap_obs'].plot()

<ipython-input-11-c01b37a40c9a> in mov_avg(x, window, min_count, axis)
      4     yy=np.ma.filled(np.ma.fix_invalid(x),np.nan)
      5     yyF=np.ma.masked_all(yy.shape)
----> 6     xtmp=bn.move_mean(yy,window,min_count=min_count,axis=axis)
      7     wd1=(window-1)/2
      8     ndim = len(yy.shape)

ValueError: Moving window (=7) must between 1 and 1, inclusive
Run Code Online (Sandbox Code Playgroud)

有人知道如何平滑我的数据吗?

jha*_*man 6

Xarray 包括用于此类操作的滚动方法。

ds['Evap_obs'].rolling(time=7).mean().plot()
Run Code Online (Sandbox Code Playgroud)

xarray 文档包含一些使用此方法的示例:http://xarray.pydata.org/en/stable/computation.html#rolling-window-operations