简体   繁体   English

将所有 xarray 数据集值替换为常量

[英]Replace all xarray dataset values with a constant

I have an xarray dataset.我有一个 xarray 数据集。 I want to make a copy of that so it has the same dimensions/coordinates/shape as the original.我想复制它,使其具有与原件相同的尺寸/坐标/形状。 That's easy.这很容易。

import xarray as xr

n_segs = 4
n_dates = 5
num_vars = 4
dims = (n_segs, n_dates)

das = [xr.DataArray(np.random.rand(*dims), dims=['seg_id', 'date'])
       for i in range(num_vars)]

ds_orig = xr.Dataset({'a': das[0], 'b': das[1], 'c': das[2], 'd': das[3]})
ds_copy = ds_orig.copy(deep=True)

Then I want to assign all the values in the copy a constant value (let's say 1).然后我想为副本中的所有值分配一个常量值(比如说 1)。 I've figured out how to do this with where :我已经想出了如何使用where来做到这一点:

ds_copy.where(ds_copy == np.nan, other=1)

but this assumes that none of my values will be nan and is a little counter-intuitive IMO.但这假设我的价值观都不是nan并且有点违反直觉的 IMO。 Is there a more robust way?有没有更健壮的方法?

I suppose I can also loop through the data variables (which is what this suggests for Pandas)...:我想我也可以循环遍历数据变量( 就是 Pandas 的建议)......:

for v in ds_copy.data_vars:
    ds_copy[v].loc[:, :] = 1

Maybe what I'm looking for here is a replace method.也许我在这里寻找的是一种replace方法。

I would recommend the loop approach because it will preserve dtypes from the original values.我会推荐循环方法,因为它会保留原始值的 dtypes。 Only one ellipsis in the loc is enough, and the .data_vars can be omitted (datasets have a dictionary interface ): loc中只有一个省略号就足够了, .data_vars可以省略(数据集有一个字典接口):

for v in ds_copy:
    ds_copy[v].loc[:] = 1

To get a more robust version of the where version, you can pass False directly to make sure other will always be used:要获得更健壮的where版本,您可以直接传递False以确保始终使用other

ds_copy.where(False, 1)

When storing ints and floats, keeping or not the dtype will probably not have any effect, however, if there are also string or boolean variables, results may change drastically.在存储整数和浮点数时,是否保留 dtype 可能不会有任何影响,但是,如果还有字符串或 boolean 变量,结果可能会发生巨大变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM