How to bin a 2D array in numpy?

前端 未结 3 958
清歌不尽
清歌不尽 2020-12-30 12:17

I\'m new to numpy and I have a 2D array of objects that I need to bin into a smaller matrix and then get a count of the number of objects in each bin to make a heatmap. I fo

3条回答
  •  情书的邮戳
    2020-12-30 13:13

    You can reshape the array to a four dimensional array that reflects the desired block structure, and then sum along both axes within each block. Example:

    >>> a = np.arange(24).reshape(4, 6)
    >>> a
    array([[ 0,  1,  2,  3,  4,  5],
           [ 6,  7,  8,  9, 10, 11],
           [12, 13, 14, 15, 16, 17],
           [18, 19, 20, 21, 22, 23]])
    >>> a.reshape(2, 2, 2, 3).sum(3).sum(1)
    array([[ 24,  42],
           [ 96, 114]])
    

    If a has the shape m, n, the reshape should have the form

    a.reshape(m_bins, m // m_bins, n_bins, n // n_bins)
    

提交回复
热议问题