[英]Round and overwrite xarray data in place
I want to round all of the values in a xarray to 2 decimal places.我想将 xarray 中的所有值四舍五入到小数点后两位。
I have tried the following:我尝试了以下方法:
def round_dim(data_arr):
data_arr.data = data_arr.data.round(decimals = 2)
return data_arr
I call it as such:我这样称呼它:
data_values = <xarray.core.dataarray.DataArray>
data_values = round_dim(data_values)
I would expect data_values
to now how the same values but rounded to 2 decimal places but this does not happen.我希望
data_values
现在如何使用相同的值但四舍五入到小数点后两位,但这并没有发生。
EDIT编辑
When I look at the data it is as follows:当我查看数据时,它如下所示:
def round_dim(data_arr):
#(data_arr.values) is [-50.406578, -50.415337, -50.42315]
data_arr.data = data_arr.data.round(decimals = 2)
#(data_arr.values) is [-50.41, -50.42, -50.42]
return data_arr
As can be seen after data_arr.data = data_arr.data.round(decimals = 2)
I do get the correct rounding.从
data_arr.data = data_arr.data.round(decimals = 2)
之后可以看出,我确实得到了正确的舍入。
However, doing:但是,做:
data_values = <xarray.core.dataarray.DataArray>
data_values = round_dim(data_values)
print(data_values.values)
I do not get the correct rounded values, instead:我没有得到正确的舍入值,而是:
[-50.409999, -50.419998, -50.419998]
I would expect the data array to look like [-50.41, -50.42, -50.42]
我希望数据数组看起来像
[-50.41, -50.42, -50.42]
If you want to apply round(decimals = 2)
to your whole dataset, you can use xarray.Dataset.map
.如果要将
round(decimals = 2)
应用于整个数据集,可以使用xarray.Dataset.map
。
It returns a copy of the original dataset with all its data rounded, it does not work in place.它返回原始数据集的副本及其所有数据四舍五入,它不能在原地工作。
import numpy as np
import xarray
dataset = xarray.Dataset()
dataset["a"] = xarray.DataArray(np.linspace(0, 1, 10))
dataset["b"] = xarray.DataArray(np.arange(10))
print(dataset)
# <xarray.Dataset>
# ...
# a (dim_0) float64 0.0 0.1111 0.2222 0.3333 ... 0.7778 0.8889 1.0
# b (dim_0) int32 0 1 2 3 4 5 6 7 8 9
def round_dim(dataset):
return dataset.map(lambda a: np.round(a, decimals=2))
dataset = round_dim(dataset)
print(dataset)
# <xarray.Dataset>
# ...
# a (dim_0) float64 0.0 0.11 0.22 0.33 0.44 0.56 0.67 0.78 0.89 1.0
# b (dim_0) int32 0 1 2 3 4 5 6 7 8 9
So the issue was to do with the dtype
of the data.所以问题与
dtype
的数据类型有关。 Apparently dtype
of float32
does not do well with .round
.显然
dtype
的float32
不适合.round
。
To fix the issue, I converted the data to dtype
float64
using .astype('float64')
and the rounding works as expected.为了解决这个问题,我使用
.astype('float64')
将数据转换为dtype
float64
,并且舍入按预期进行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.