[英]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.