简体   繁体   English

如何通过在python xarray中添加额外的维度将一个数组拆分为多个数组?

[英]How to split one array in multiple arrays by adding an extra dimension in python xarray?

I have the following xarray : 我有以下xarray

import xarray as xr
import numpy as np
import pandas as pd

da = xr.DataArray(np.random.rand(25, 6),
                   [('time', pd.date_range('2000-01-01', periods=25)),
                    ('space', ['IA', 'IL', 'IN', 'VA', 'VL', 'VN'])])

Where da.shape yields (25, 6) . 其中da.shape产生(25, 6) da.shape (25, 6)

I would like to split the 25 into 5 x 5 such that I get a 3D shape in the following form: (5, 5, 6) . 我想将25分割成5 x 5 ,以便得到以下形式的3D形状: (5, 5, 6)

I honestly have no idea where to start. 老实说,我不知道从哪里开始。 I looked up the docs and could not find any solution. 我查了一下文档,找不到任何解决方案。 I know I seek only a vectorized solution (ie no loops and list.append() stuff, because it will be too costly otherwise. 我知道我只寻求矢量化的解决方案(即没有循环和list.append()东西,因为否则会太昂贵。

Can you help me with a solution to this problem? 您能帮我解决这个问题吗?

UPDATE: 更新:

With np.split(da, 5) I managed to create a list of 5 xarray s inside with exactly the data I need. 使用np.split(da, 5)我设法在其中创建了5个xarraylistxarray包含我所需的数据。 How do I make this step, but instead of converting to list , it stays an xarray , but it has one extra dimension? 我如何进行此步骤,但没有转换为list ,而是保留了xarray ,但又增加了一个维度?

The solution I found was by using np.resize : 我发现的解决方案是使用np.resize

da_new = np.resize(da, (5,5,6))

Where (as expected) da_new.shape yields (5, 5, 6) . 哪里(如预期的那样) da_new.shape产生(5, 5, 6) da_new.shape (5, 5, 6) This works relatively quickly as well. 这也相对较快地工作。

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

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