繁体   English   中英

多维数组上的Numpy直方图

[英]Numpy histogram on multi-dimensional array

给定np.array的形状(n_days, n_lat, n_lon) ,我想计算每个lat-lon单元的固定bin的直方图(即每日值的分布)。

解决这个问题的一个简单方法是遍历单元格并为每个单元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

但这不起作用,因为就地添加运算符(+ =)似乎不支持同一单元格的多个更新。

彼得,彼得

您可以使用numpy.apply_along_axis来消除循环。

hist, bin_edges = apply_along_axis(lambda x: histogram(x, bins=bins), 0, B)

也许这有用吗?:

import numpy as np
n_days=31
n_lat=10
n_lon=10
n_bins=10
bins = np.linspace(0, 1.0, n_bins)
B = np.random.rand(n_days, n_lat, n_lon)


# flatten to 1D
C=np.reshape(B,n_days*n_lat*n_lon)
# use digitize to get the index of the bin to which the numbers belong
D=np.digitize(C,bins)-1
# reshape the results back to the original shape
result=np.reshape(D,(n_days, n_lat, n_lon))

暂无
暂无

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

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