如何对矩阵进行装箱 [英] How to bin a matrix

查看:101
本文介绍了如何对矩阵进行装箱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

numpy.histogram(data,bins)是一种非常快速有效的方法,用于计算数据数组中有多少个元素落入由数组bins定义的bin中.是否有等效的功能来解决以下问题?我有一个R行乘C列的矩阵.我想使用bins给定的定义来对矩阵的每一行进行装箱.结果应该是具有R行,列数等于容器数的另一个矩阵.

numpy.histogram(data, bins) is a very fast and efficient way to calculate how many elements of the data array fall in a bin defined by the array bins. Is there an equivalent function to solve the following problem?. I have a matrix with R rows times C columns. I want to bin each row of the matrix using the definition given by bins. The result should be a further matrix with R rows, and with the number of column equal to the number of bins.

我尝试使用函数numpy.histogram(data,bins)作为输入矩阵,但是我发现该矩阵被视为具有R * C元素的数组.然后,结果是一个包含Nbins元素的数组.

I tried to use the function numpy.histogram(data, bins) giving as input a matrix, but I found that the matrix is treated as an array with R*C elements. Then, the result is an array with Nbins elements.

推荐答案

如果您将其应用于具有许多行的数组,则此函数将为您提供一些加速,但需要付出一些代价临时记忆.

If you're applying this to an array that has many rows this function will give you some speed up at the cost of some temporary memory.

def hist_per_row(data, bins):

    data = np.asarray(data)

    assert np.all(bins[:-1] <= bins[1:])
    r, c = data.shape
    idx = bins.searchsorted(data)
    step = len(bins) + 1
    last = step * r
    idx += np.arange(0, last, step).reshape((r, 1))
    res = np.bincount(idx.ravel(), minlength=last)
    res = res.reshape((r, step))
    return res[:, 1:-1]

最后一行的res[:, 1:-1]与numpy.histogram一致,该数组返回一个len为len(bins) - 1的数组,但是如果要计算小于和大于bins[0]的值,则可以将其删除和bins[-1].

The res[:, 1:-1] on the last line is to be consistent with numpy.histogram which returns an array with len len(bins) - 1, but you could drop it if you want to count values that are less than and greater than bins[0] and bins[-1] respectively.

这篇关于如何对矩阵进行装箱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆