给定一个形状为(n_days, n_lat, n_lon)
的 np.array 数组,我想为每个经纬度单元格计算具有固定区间的直方图(即每日值的分布)。
问题的简单解决方法是循环遍历单元格并对每个单元格调用np.histogram
函数:
bins = np.linspace(0, 1.0, 10)
B = np.rand(n_days, n_lat, n_lon)
H = np.zeros((n_bins, n_lat, n_lon), dtype=np.int32)
for lat in range(n_lat):
for lon in range(n_lon):
H[:, lat, lon] = np.histogram(A[:, lat, lon], bins=bins)[0]
# note: code not tested
但这种方法速度较慢。有没有更有效率的解决方案,不需要使用循环?
我研究了np.searchsorted以获取B中每个值的bin索引,然后使用fancy indexing来更新H:
bin_indices = bins.searchsorted(B)
H[bin_indices.ravel(), idx[0], idx[1]] += 1 # where idx is a index grid given by np.indices
# note: code not tested
但是这样做行不通,因为就地加法运算符(+=)似乎不支持同一单元格的多次更新。
谢谢, 彼得
np.histogram2d
函数并带上weights
关键字参数。 - Jaimenp.histogramdd
函数。 - Jaime