这是一个玩具示例,但我有2个数据帧; (1)rows = samples,cols = attributes; (2)rows = samples,cols = metadata-fields。
我希望concat
或merge
创建三维xr.DataArray
。我已经多次这样做但我无法弄清楚为什么它在这种情况下不起作用?我想concat
沿着patient_id
轴获得3D xr.DataArray
。
为什么不xr.concat
构建三维DataArray
?我认为我错误地使用dim
参数,因为沿着新轴应该concat
但是有没有办法沿现有轴做这个?
我正在尝试使用Create DataArray from Dict of 2D DataFrames/Arrays中的方法,但它无效。我让merge
工作,但它将它放入DataSet
w / 2数据变量
np.random.seed(0)
patient_ids = ["patient_%d"%_ for _ in range(42)]
attr_ids = ["attr_%d"%_ for _ in range(481)]
meta_ids = ["meta_%d"%_ for _ in range(32)]
DA_A = xr.DataArray(pd.DataFrame(np.random.random((42,481)),
index=patient_ids,
columns=attr_ids),
dims=["patient_id","attribute"])
DA_B = xr.DataArray(pd.DataFrame(np.random.random((42,32)),
index=patient_ids,
columns=meta_ids),
dims=["patient_id","metadata"])
DA_A.coords
# Coordinates:
# * patient_id (patient_id) object 'patient_0' 'patient_1' 'patient_2' ...
# * attribute (attribute) object 'attr_0' 'attr_1' 'attr_2' 'attr_3' ...
DA_B.coords
# Coordinates:
# * patient_id (patient_id) object 'patient_0' 'patient_1' 'patient_2' ...
# * metadata (metadata) object 'meta_0' 'meta_1' 'meta_2' 'meta_3' ...
xr.concat([DA_A, DA_B], dim="patient_id")
# KeyError: 'attribute'
答案 0 :(得分:1)
您不能(还)连接具有不同维度的DataArrays。您需要首先明确地广播它们,例如,
In [38]: xr.concat(xr.broadcast(DA_A, DA_B), dim="patient_id")
Out[38]:
<xarray.DataArray (patient_id: 84, attribute: 481, metadata: 32)>
array([[[ 0.5488135 , 0.5488135 , 0.5488135 , ..., 0.5488135 ,
0.5488135 , 0.5488135 ],
...,
[ 0.79649197, 0.97094708, 0.95542135, ..., 0.37856775,
0.65855316, 0.37893685]]])
Coordinates:
* attribute (attribute) object 'attr_0' 'attr_1' 'attr_2' 'attr_3' ...
* metadata (metadata) object 'meta_0' 'meta_1' 'meta_2' 'meta_3' ...
* patient_id (patient_id) object 'patient_0' 'patient_1' 'patient_2' ...
但正如jhamman在你的问题评论中提到的那样,实际上你可能会发现使用单个Dataset
对象更容易,有两个不同的变量,例如,
In [39]: xr.Dataset({'A': DA_A, 'B': DA_B})
Out[39]:
<xarray.Dataset>
Dimensions: (attribute: 481, metadata: 32, patient_id: 42)
Coordinates:
* patient_id (patient_id) object 'patient_0' 'patient_1' 'patient_2' ...
* attribute (attribute) object 'attr_0' 'attr_1' 'attr_2' 'attr_3' ...
* metadata (metadata) object 'meta_0' 'meta_1' 'meta_2' 'meta_3' ...
Data variables:
A (patient_id, attribute) float64 0.5488 0.7152 0.6028 0.5449 ...
B (patient_id, metadata) float64 0.2438 0.8216 0.9237 0.3999 ...