给定一个np.数组的形状(n_days, n_lat, n_lon)
,我想计算一个直方图与固定箱为每个lat-lon细胞(即每日值的分布)。
解决这个问题的一个简单方法是遍历单元格,并为每个单元格调用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索引,然后使用花哨的索引更新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
但这并不起作用,因为原地加法运算符(+=)似乎不支持同一单元格的多次更新。
thx彼得
2条答案
按热度按时间z9zf31ra1#
您可以使用
numpy.apply_along_axis()
来消除循环。e5nszbig2#
也许这能起作用: