Pet*_*fer 5 python arrays numpy histogram
给定np.array的形状(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
Run Code Online (Sandbox Code Playgroud)
但这很慢.有没有更有效的解决方案,不涉及循环?
我调查np.searchsorted了每个值的bin索引B,然后使用花式索引来更新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
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为就地添加运算符(+ =)似乎不支持同一单元格的多个更新.
彼得,彼得
您可以使用numpy.apply_along_axis()它来消除循环。
import numpy as np
hist, bin_edges = np.apply_along_axis(lambda x: np.histogram(x, bins=bins), 0, B)
Run Code Online (Sandbox Code Playgroud)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           2250 次  |  
        
|   最近记录:  |