首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用scipy/numpy将python中的数据打包

使用scipy/numpy将python中的数据打包
EN

Stack Overflow用户
提问于 2011-05-29 01:43:00
回答 6查看 206.2K关注 0票数 125

有没有一种更有效的方法来在预先指定的存储箱中取一个数组的平均值?例如,我有一个数字数组和一个对应于该数组中bin开始和结束位置的数组,我想只取这些bin中的平均值?我有下面的代码可以做到这一点,但我想知道如何减少和改进它。谢谢。

代码语言:javascript
复制
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
EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2011-05-29 01:53:59

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

代码语言:javascript
复制
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()

代码语言:javascript
复制
bin_means = (numpy.histogram(data, bins, weights=data)[0] /
             numpy.histogram(data, bins)[0])

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

票数 203
EN

Stack Overflow用户

发布于 2014-11-12 18:19:27

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

对于与前面答案相同的示例,Scipy解决方案为

代码语言:javascript
复制
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]
票数 46
EN

Stack Overflow用户

发布于 2014-02-12 04:17:51

不确定为什么这个线程会被破坏;但这是2014年批准的答案,它应该快得多:

代码语言:javascript
复制
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
票数 17
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6163334

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档