【问题标题】:python xarray - update subset of valuespython xarray - 更新值的子集
【发布时间】:2022-10-22 17:49:16
【问题描述】:

我需要更新 Xarray DataArray 中的值。我只想更新某些值,它们与它们的坐标一起存储在数据框中。

人们也可以将问题重新表述为 (i) 更新 DataArray 中值的非连续(非矩形)区域和 (ii) 使用匹配坐标上的新值左连接数据集并重写旧值。

初始数据数组(数据集):

import xarray as xr
import pandas as pd

ds = xr.Dataset(
    data_vars = {"x": (("a", "b"), np.zeros((3, 4)))},
    coords = {"a": np.arange(3), "b": np.arange(4)})
ds.x.values    

array([[0., 0., 0., 0.],
      [0., 0., 0., 0.],
      [0., 0., 0., 0.]])

分配坐标的新值:

new_val = pd.DataFrame([
    (0, 1, 10),
    (1, 0, 11),
    (2, 2, 12)],
    columns=['a', 'b', 'x'])

我想得到的结果:

array([[0., 10., 0., 0.],
      [11., 0., 0., 0.],
      [0., 0., 12., 0.]])

我试图在Combining dataAssigning values with indexing turials 中使用方法,但到目前为止还没有运气。

【问题讨论】:

    标签: python python-xarray


    【解决方案1】:

    使用combine_first 可以实现结果。

    # set index and convert to xr Dataset
    new_val_idx = new_val.set_index(['a', 'b'])
    new_val_ds = xr.Dataset.from_dataframe(new_val_idx)
    
    combined = new_val_ds.combine_first(ds)
    combined.x.values
    
    array([[ 0., 10.,  0.,  0.],
           [11.,  0.,  0.,  0.],
           [ 0.,  0., 12.,  0.]])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-20
      • 2021-10-29
      • 2021-06-28
      • 1970-01-01
      • 2019-06-08
      • 2018-12-24
      • 2018-08-17
      • 2023-04-09
      相关资源
      最近更新 更多