使用 scipy/numpy 在 python 中对数据进行分箱
- 2025-02-13 08:36:00
- admin 原创
- 36
问题描述:
有没有更有效的方法来对预指定容器中的数组取平均值?例如,我有一个数字数组和一个对应于该数组中容器起始和终止位置的数组,我只想在这些容器中取平均值?我有下面的代码可以做到这一点,但我想知道如何减少和改进它。谢谢。
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
解决方案 1:
它可能更快并且更容易使用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])
亲自尝试一下哪一个更快...:)
解决方案 2:
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]
解决方案 3:
不确定为什么这个线程会被删除;但是这里有一个 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))
这本质上与我之前发布的解决方案相同;但现在包装在一个漂亮的界面中,并带有测试和所有内容:)
解决方案 5:
我想补充一点,为了回答使用 histogram2d python 查找平均 bin 值的问题,scipy 也有一个专门设计用于计算一组或多组数据的二维 binned 统计数据的函数
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是该函数针对高维数据集的泛化
解决方案 6:
另一种方法是使用 ufunc.at。此方法在指定索引处就地应用所需的操作。我们可以使用 searchsorted 方法获取每个数据点的 bin 位置。然后,每当我们在 bin_indexes 遇到索引时,我们就可以使用 at 将 bin_indexes 给出的索引处的直方图位置增加 1。
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)
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD