【问题标题】:python-xarray: Compute the absolute values of a datasetpython-xarray:计算数据集的绝对值
【发布时间】:2017-10-27 17:49:24
【问题描述】:

np.fabsxr.DataArray 上运行良好,但在 xr.Dataset 上运行良好。

data = xr.DataArray(np.random.randn(2, 3), coords={'x': ['a', 'b']}, dims=('x', 'y'))
ds = xr.Dataset({'foo': data, 'bar': ('x', [1, 2]), 'baz': np.pi})
np.fabs(ds)
TypeError: ufunc 'fabs' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
np.fabs(ds['foo'])
<xarray.DataArray 'foo' (x: 2, y: 3)>
array([[ 0.384305,  0.161676,  0.07573 ],
       [ 0.789885,  1.299188,  1.965528]])
Coordinates:
  * x        (x) <U1 'a' 'b'
Dimensions without coordinates: y

任何想法如何将其应用于xr.Dataset

我可以遍历 xr.Dataset 中的变量(见下文),但我不确定是否有更有效的方法

for i, var in enumerate(ds.data_vars):
    ds[var] = np.fabs(ds[var])

【问题讨论】:

    标签: python-xarray numpy-ufunc


    【解决方案1】:

    使用 do 最简单的方法是使用 Python 的内置 abs() 函数:abs(ds) 应该这样做。

    【讨论】:

      【解决方案2】:

      您正在Dataset 上寻找apply 方法。

      In [10]: ds.apply(np.fabs)
      Out[10]:
      <xarray.Dataset>
      Dimensions:  (x: 2, y: 3)
      Coordinates:
        * x        (x) <U1 'a' 'b'
      Dimensions without coordinates: y
      Data variables:
          foo      (x, y) float64 0.2069 2.685 1.815 1.674 1.038 0.5664
          baz      float64 3.142
          bar      (x) float64 1.0 2.0
      

      【讨论】:

      猜你喜欢
      • 2020-07-02
      • 1970-01-01
      • 2018-12-11
      • 1970-01-01
      • 1970-01-01
      • 2022-10-22
      • 2012-08-16
      • 2018-08-17
      • 1970-01-01
      相关资源
      最近更新 更多