用scipy / numpy在python中分箱数据

问题描述 投票:87回答:6

是否有更有效的方法在预先指定的箱中取平均数组?例如,我有一个数字数组和一个对应于该数组中bin开始和结束位置的数组,我想在这些数据库中取平均值?我有下面的代码,但我想知道如何减少和改进它。谢谢。

from scipy import *
from numpy import *

def get_bin_mean(a, b_start, b_end):
    ind_upper = nonzero(a >= b_start)[0]
    a_upper = a[ind_upper]
    a_range = a_upper[nonzero(a_upper < b_end)[0]]
    mean_val = mean(a_range)
    return mean_val


data = rand(100)
bins = linspace(0, 1, 10)
binned_data = []

n = 0
for n in range(0, len(bins)-1):
    b_start = bins[n]
    b_end = bins[n+1]
    binned_data.append(get_bin_mean(data, b_start, b_end))

print binned_data
python numpy scipy scientific-computing
6个回答
159
投票

使用numpy.digitize()可能更快更容易:

import numpy
data = numpy.random.random(100)
bins = numpy.linspace(0, 1, 10)
digitized = numpy.digitize(data, bins)
bin_means = [data[digitized == i].mean() for i in range(1, len(bins))]

另一种方法是使用numpy.histogram()

bin_means = (numpy.histogram(data, bins, weights=data)[0] /
             numpy.histogram(data, bins)[0])

试试自己哪一个更快...... :)


33
投票

Scipy(> = 0.11)函数scipy.stats.binned_statistic专门解决了上述问题。

对于与之前答案中相同的示例,Scipy解决方案将是

import numpy as np
from scipy.stats import binned_statistic

data = np.random.rand(100)
bin_means = binned_statistic(data, data, bins=10, range=(0, 1))[0]

15
投票

不知道为什么这个线程被恶化了;但这是2014年批准的答案,应该快得多:

import numpy as np

data = np.random.rand(100)
bins = 10
slices = np.linspace(0, 100, bins+1, True).astype(np.int)
counts = np.diff(slices)

mean = np.add.reduceat(data, slices[:-1]) / counts
print mean

4
投票

numpy_indexed包(免责声明:我是它的作者)包含有效执行此类操作的功能:

import numpy_indexed as npi
print(npi.group_by(np.digitize(data, bins)).mean(data))

这与我之前发布的解决方案基本相同;但现在包装在一个漂亮的界面,测试和所有:)


1
投票

我想补充,并回答问题find mean bin values using histogram2d python,scipy也有一个专门为compute a bidimensional binned statistic for one or more sets of data设计的功能

import numpy as np
from scipy.stats import binned_statistic_2d

x = np.random.rand(100)
y = np.random.rand(100)
values = np.random.rand(100)
bin_means = binned_statistic_2d(x, y, values, bins=10).statistic

函数scipy.stats.binned_statistic_dd是更高维数据集的此函数的推广


0
投票

另一种方法是使用ufunc.at。该方法适用于指定索引处的所需操作。我们可以使用searchsorted方法获取每个数据点的bin位置。然后我们可以使用at在bin_indexes给出的索引处将直方图的位置递增1,每次我们在bin_indexes处遇到索引。

np.random.seed(1)
data = np.random.random(100) * 100
bins = np.linspace(0, 100, 10)

histogram = np.zeros_like(bins)

bin_indexes = np.searchsorted(bins, data)
np.add.at(histogram, bin_indexes, 1)
© www.soinside.com 2019 - 2024. All rights reserved.