用scipy/numpy在python中分箱数据

95 python numpy scientific-computing scipy

是否有更有效的方法在预先指定的箱中取平均数组?例如,我有一个数字数组和一个对应于该数组中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
Run Code Online (Sandbox Code Playgroud)

Sve*_*ach 164

它可能更快更容易使用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))]
Run Code Online (Sandbox Code Playgroud)

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

bin_means = (numpy.histogram(data, bins, weights=data)[0] /
             numpy.histogram(data, bins)[0])
Run Code Online (Sandbox Code Playgroud)

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

  • @user:我不知道哪一个对您的数据和参数更快.这两种方法都应该比你的方法更快,并且我希望`histogram()`方法对于大量的bin来说更快.但你必须要自我描述,我不能为你做这件事. (4认同)

div*_*nex 37

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]
Run Code Online (Sandbox Code Playgroud)


Eel*_*orn 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
Run Code Online (Sandbox Code Playgroud)

  • 您在回答另一个问题。例如,您的“均值[0] = np.mean(data [0:10])”,而正确的答案应为“ np.mean(data [data &lt;data] 10])”。 (2认同)

Eel*_*orn 5

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

import numpy_indexed as npi
print(npi.group_by(np.digitize(data, bins)).mean(data))
Run Code Online (Sandbox Code Playgroud)

这基本上与我之前发布的解决方案相同;但现在包裹在一个不错的界面中,包括测试和所有功能:)


小智 5

我想补充一点,也是为了回答使用 histogram2d python 查找平均分箱值的问题,scipy 还具有一个专门设计用于计算一组或多组数据的二维分箱统计量的函数

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
Run Code Online (Sandbox Code Playgroud)

函数scipy.stats.binned_statistic_dd是该函数针对更高维度数据集的泛化