<p>首先,一张便条。创建一个新的DataArray,每天复制相同的空间数据,持续3个月,可能会占用大量磁盘空间而没有太大意义。我宁愿在您每次需要特定日期的数据时查询季节数据数组。
但是,如果您真的需要执行此操作,并回答您的问题,我认为最直接的方法是:</p>
<ol>
<li>首先,创建一个新容器np.ndarray公司是个好主意。在</li>
<li>然后,建立日期索引</li>
<li>查询你原来的季节数据数组</li>
<li>最后,使用维度时间创建一个新的DataArray。在</li>
</ol>
<p>在下面的示例中,我创建了一个用于测试的季节数据数组。如果我完全理解您的问题,那么在第二部分(通过foo的创建),您应该能够使用原始数组而不需要做太多更改。在</p>
<p>我们开始吧。首先是进口:</p>
<pre><code>import xarray as xr
import numpy as np
import pandas as pd
</code></pre>
<p>创建所需大小的空容器。在</p>
^{pr2}$
<p>用虚拟值填充它。在</p>
<pre><code>data_s[0] = 0.5
data_s[1] = 0.9
data_s[2] = 0.8
data_s[3] = 0.45
</code></pre>
<p>创建虚拟坐标。在</p>
<pre><code>x = y = np.arange(10)
</code></pre>
<p>创建季节索引。在</p>
<pre><code>seasons = ["spring", "summer", "autumn", "winter"]
</code></pre>
<p>最后,创建DataArray。在</p>
<pre><code>bar = xr.DataArray(data_s, coords=[seasons, x, y], dims=['season', 'x', 'y'])
</code></pre>
<p>bar是要从中提取季节值的DataArray。
现在对单个日期重复相同的操作。在</p>
<p>创建一个2000天的容器数组,我们将用每个季节的数据填充它。在</p>
<pre><code>data = np.ones((2000, 10, 10))
x = y = np.arange(10)
dates = pd.date_range('2000-01-01', periods=2000)
</code></pre>
<p>这里我假设北半球的季节从月初一开始(借用自<a href="https://stackoverflow.com/a/44124490/5326322">here</a>)。
当然,您可以很容易地编写一个更好的函数,例如使用一年中的某一天来获取季节。在</p>
<pre><code>season = np.array((dates.month %12 + 3)//3)
</code></pre>
<p>创建一个字典,将上面的数字转换为之前在bar中指定的季节字符串</p>
<pre><code>seas_to_num = {1:"spring", 2:"summer", 3:"autumn", 4:"winter"}
</code></pre>
<p>我们用bar[season]上的值填充每天的数组。在</p>
<pre><code>for date, seas in enumerate(season):
data[date] = bar.sel(season=seas_to_num[seas])
</code></pre>
<p>最后,我们创建DataArray。在</p>
<pre><code>foo = xr.DataArray(data, coords=[dates, x, y], dims=['time', 'x', 'y'])
</code></pre>
<p>现在选择4月5日,我们得到春天的值。在</p>
<pre><code>In [1]: foo.sel(time=pd.to_datetime("5/4/2001"))
Out[1]:
array([[0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9],
[0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9],
[0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9],
[0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9],
[0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9],
[0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9],
[0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9],
[0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9],
[0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9],
[0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9]])
Coordinates:
time datetime64[ns] 2001-05-03
* x (x) int32 0 1 2 3 4 5 6 7 8 9
* y (y) int32 0 1 2 3 4 5 6 7 8 9
</code></pre>