我有一个多维数据对象,它有一个时间轴。我需要根据常规时间序列(例如每小时或每天)来分组数据(以便随后计算每个时间段内的相关性并获得相关时间序列)。但是,当我尝试使用groupby_bins
时,我会TypeError: Cannot cast ufunc less input from dtype('<m8[ns]') to dtype('<m8') with casting rule 'same_kind'
:
# xr is xarray; pd is pandas
In [109]: C = numpy.random.randint(-2000, 2000, dtype='int16', size=(5000, 56, 20))
In [110]: D = xr.DataArray(C, dims=("time", "scanpos", "channel"), coords={"time": pd.date_range("2000-01-01T00:00:00", periods=5000, freq='1min')})
In [111]: D.groupby_bins("time", pd.date_range(*D["time"].data[[0,-1]], freq="1H"))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-111-7e7cda1ad060> in <module>()
----> 1 D.groupby_bins("time", pd.date_range(*D["time"].data[[0,-1]], freq="1H"))
/dev/shm/gerrit/venv/stable-3.5/lib/python3.5/site-packages/xarray/core/common.py in groupby_bins(self, group, bins, right, labels, precision, include_lowest, squeeze)
397 cut_kwargs={'right': right, 'labels': labels,
398 'precision': precision,
--> 399 'include_lowest': include_lowest})
400
401 def rolling(self, min_periods=None, center=False, **windows):
/dev/shm/gerrit/venv/stable-3.5/lib/python3.5/site-packages/xarray/core/groupby.py in __init__(self, obj, group, squeeze, grouper, bins, cut_kwargs)
190 raise TypeError("Can't specify both `grouper` and `bins`.")
191 if bins is not None:
--> 192 binned = pd.cut(group.values, bins, **cut_kwargs)
193 new_dim_name = group.name + '_bins'
194 group = DataArray(binned, group.coords, name=new_dim_name)
/dev/shm/gerrit/venv/stable-3.5/lib/python3.5/site-packages/pandas/tools/tile.py in cut(x, bins, right, labels, retbins, precision, include_lowest)
112 else:
113 bins = np.asarray(bins)
--> 114 if (np.diff(bins) < 0).any():
115 raise ValueError('bins must increase monotonically.')
116
TypeError: Cannot cast ufunc less input from dtype('<m8[ns]') to dtype('<m8') with casting rule 'same_kind'
如何使用xarray
s groupby_bins
的时间轴?我尝试使用匹配dtypes的时间轴,但将dtype
传递给pd.date_range
似乎没有效果,即使dtypes相同(不确定为什么它们不在这个玩具示例中,但那是一个错误仍然存在。
P.S。我也很满意完全绕过pd.date_range
的解决方案。
答案 0 :(得分:0)
groupby_bins
用于数字数据,但没有固有的原因,它不适用于日期(这确实有点令人困惑)。解决分组日期问题的最简单方法是使用resample
method:
D.resample("time", "1H")