我不知道如何从xr.Dataset
对象中实际提取数据。我不知道如何获取个人价值观。如何像使用DataArrays一样从数据集中提取值(点值、向量、数组等)?
np.random.seed(0)
DA_data = xr.DataArray(np.random.random((3,2,10,100)), dims=["targets","accuracy","metrics","attributes"], name="Data")
DA_data.coords["attributes"] = ["attr_%d"%_ for _ in range(100)]
# DA_data.coords
# Coordinates:
# * targets (targets) int64 0 1 2
# * accuracy (accuracy) int64 0 1
# * metrics (metrics) int64 0 1 2 3 4 5 6 7 8 9
# * attributes (attributes) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ...
# Indexing DataArray
#DA_data.sel(targets=0, accuracy=0, metrics=0, attributes="attr_5").values
#array(0.6458941130666561)
float(DA_data.sel(targets=0, accuracy=0, metrics=0, attributes="attr_5").values)
#0.6458941130666561
# Indexing Dataset
DS_data = DA_data.to_dataset()
# DS_data
# <xarray.Dataset>
# Dimensions: (accuracy: 2, attributes: 100, metrics: 10, targets: 3)
# Coordinates:
# * targets (targets) int64 0 1 2
# * accuracy (accuracy) int64 0 1
# * metrics (metrics) int64 0 1 2 3 4 5 6 7 8 9
# * attributes (attributes) <U7 'attr_0' 'attr_1' 'attr_2' 'attr_3' ...
# Data variables:
# Data (targets, accuracy, metrics, attributes) float64 0.5488 ...
DS_data.sel(targets=0, accuracy=0, metrics=0, attributes="attr_5").values
# <bound method Mapping.values of <xarray.Dataset>
# Dimensions: ()
# Coordinates:
# targets int64 0
# accuracy int64 0
# metrics int64 0
# attributes <U7 'attr_5'
# Data variables:
# Data float64 0.6459>
float(DS_data.sel(targets=0, accuracy=0, metrics=0, attributes="attr_5").values)
# ---------------------------------------------------------------------------
# TypeError Traceback (most recent call last)
# <ipython-input-408-e0c88e8541d8> in <module>()
# 38 # Data variables:
# 39 # Data float64 0.6459>
# ---> 40 float(DS_data.sel(targets=0, accuracy=0, metrics=0, attributes="attr_5").values)
# TypeError: float() argument must be a string or a number, not 'method'
这有点令人困惑,但.values
在Dataset
和DataArray
:上的工作方式不同
DataArray.values
返回一个NumPy数组。这种行为与熊猫是一致的Dataset.values()
返回组成数据集的DataArray对象的列表(Python 2)或ValuesView(Python 3)。这种行为与满足Python的Mapping
接口的Dataset
一致
要从Dataset
中提取值,需要通过数据集类似字典的接口(例如float(DA_data['Data'])
或float(DA_data.values()[0])
)提取DataArray
。您不能直接将Dataset
转换为float或NumPy数组,就像使用Python dict一样。