使用scipy/numpy在python中合并数据 [英] binning data in python with scipy/numpy
本文介绍了使用scipy/numpy在python中合并数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有更有效的方法来对预先指定的bin中的数组取平均值?例如,我有一个数字数组以及一个与该数组中bin起始和结束位置相对应的数组,我只想取这些bin中的均值?我下面有执行此操作的代码,但我想知道如何减少和改进它.谢谢.
is there a more efficient way to take an average of an array in prespecified bins? for example, i have an array of numbers and an array corresponding to bin start and end positions in that array, and I want to just take the mean in those bins? I have code that does it below but i am wondering how it can be cut down and improved. thanks.
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
推荐答案
使用一种替代方法是使用 numpy.histogram()
:
An alternative to this is to use numpy.histogram()
:
bin_means = (numpy.histogram(data, bins, weights=data)[0] /
numpy.histogram(data, bins)[0])
亲自尝试哪一个更快...:)
Try for yourself which one is faster... :)
这篇关于使用scipy/numpy在python中合并数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文