有没有一种更有效的方法来在预先指定的存储箱中取一个数组的平均值?例如,我有一个数字数组和一个对应于该数组中bin开始和结束位置的数组,我想只取这些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
发布于 2011-05-29 01:53:59
使用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])
你自己试试哪一个更快...:)
发布于 2014-11-12 18:19:27
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]
发布于 2014-02-12 04:17:51
不确定为什么这个线程会被破坏;但这是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
https://stackoverflow.com/questions/6163334
复制相似问题