如何在numpy中对2D数组进行装箱? [英] How to bin a 2D array in numpy?
问题描述
我是numpy的新手,我有一个2D对象数组,需要将它们合并到一个较小的矩阵中,然后获取每个容器中对象的数量计数以制作热图.我在这个线程上按照答案 来创建垃圾箱并执行计数一个简单的数组,但我不确定如何将其扩展到2维.这是我到目前为止的内容:
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 followed the answer on this thread to create the bins and do the counts for a simple array but I'm not sure how to extend it to 2 dimensions. Here's what I have so far:
data_matrix = numpy.ndarray((500,500),dtype=float)
# fill array with values.
bins = numpy.linspace(0,50,50)
digitized = numpy.digitize(data_matrix, bins)
binned_data = numpy.ndarray((50,50))
for i in range(0,len(bins)):
for j in range(0,len(bins)):
k = len(data_matrix[digitized == i:digitized == j]) # <-not does not work
binned_data[i:j] = k
P.S.数组上的[digitized == i]
表示法将返回一个二进制值数组.我在任何地方都找不到有关此符号的文档.链接将不胜感激.
P.S. the [digitized == i]
notation on an array will return an array of binary values. I cannot find documentation on this notation anywhere. A link would be appreciated.
推荐答案
您可以将数组重塑为反映所需块结构的四维数组,然后沿每个块内的两个轴求和.示例:
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]])
如果a
具有形状m, n
,则重塑应具有以下形式
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)
这篇关于如何在numpy中对2D数组进行装箱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!