【问题标题】:replace values in xarray dataset with None用 None 替换 xarray 数据集中的值
【发布时间】:2018-10-11 22:20:15
【问题描述】:

我想用 None 替换 xarray 数据集中变量中的值。我尝试了这种方法,但没有奏效:

da[da['var'] == -9999.]['var'] = None

我收到此错误:*** TypeError: unhashable type: 'numpy.ndarray'

我可以在这里使用 numpy replace 之类的东西吗? da 是 xarray 数据集。这是da 的样子:

<xarray.Dataset>
Dimensions:  (band: 1, time: 3, x: 4258, y: 2334)
Coordinates:
  * band     (band) int32 1
  * y        (y) float64 4.406e+06 4.406e+06 4.406e+06 4.406e+06 4.406e+06 ...
  * x        (x) float64 1.125e+05 1.126e+05 1.127e+05 1.128e+05 1.129e+05 ...
  * time     (time) datetime64[ns] 2005-12-31 2006-12-31 2007-12-31
Data variables:
    var      (time, band, y, x) float32 dask.array<shape=(3, 1, 2334, 4258), chunksize=(1, 1, 2334, 4258)>

这是 da.var 的样子:

<xarray.DataArray 'var' (time: 3, band: 1, y: 2334, x: 4258)>
dask.array<shape=(3, 1, 2334, 4258), dtype=float32, chunksize=(1, 1, 2334, 4258)>
Coordinates:
  * band     (band) int32 1
  * y        (y) float64 4.406e+06 4.406e+06 4.406e+06 4.406e+06 4.406e+06 ...
  * x        (x) float64 1.125e+05 1.126e+05 1.127e+05 1.128e+05 1.129e+05 ...
  * time     (time) datetime64[ns] 2005-12-31 2006-12-31 2007-12-31
Attributes:
    transform:   (90.0, 0.0, 112500.0, 0.0, -90.0, 4406400.0, 0.0, 0.0, 1.0)
    crs:         +ellps=GRS80 +no_defs +proj=utm +towgs84=0,0,0,0,0,0,0 +unit...
    res:         (90.0, 90.0)
    is_tiled:    1
    nodatavals:  (-9999.0,)

【问题讨论】:

  • 通常会用np.nan 替换缺失值。这是一个选项吗?
  • 显示你的da
  • @jhamman,当然 np.nan 也可以工作
  • @RafaelC 更新为显示 da

标签: python xarray


【解决方案1】:

执行此操作的标准方法是使用 where: http://xarray.pydata.org/en/latest/indexing.html#masking-with-where

# Note that I'm going to use `ds` instead of the OP's `da`

# replace all values equal to -9999 with np.nan
ds_masked = ds.where(ds['var'] != -9999.)  

【讨论】:

  • 感谢@jhamman,不知何故这似乎无法解决问题,即我将ds_masked 保存到磁盘并且-9999 仍然存在
  • 我编辑了 jhamman 的答案——他应该写 ds.where(ds['var'] != -9999.),而不是 ds.where(ds['var'] == -9999.)——这与你想要的相反。希望这对你有用!
  • 谢谢@shoyer。事实上,我的比较是错误的。
猜你喜欢
  • 1970-01-01
  • 2016-06-08
  • 2021-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多