【发布时间】:2019-01-07 22:57:26
【问题描述】:
这是一个更复杂的实际应用程序的简短完整示例。
使用的库:
import numpy as np
import scipy as sp
import scipy.stats as scist
import matplotlib.pyplot as plt
from itertools import zip_longest
数据:
我有一个数组,其中包含用 start 和 end 定义的不规则 bin,例如像这样(在实际情况下,这种格式是给定的,因为它是另一个进程的输出):
bin_starts = np.array([0, 93, 184, 277, 368])
bin_ends = np.array([89, 178, 272, 363, 458])
我与之结合:
bns = np.stack(zip_longest(bin_starts, bin_ends)).flatten()
bns
>>> array([ 0, 89, 93, 178, 184, 272, 277, 363, 368, 458])
给出一个规则交替的长短间隔序列,所有的长度都是不规则的。 这是给定长间隔和短间隔的草图表示:
我有一堆时间序列数据,类似于下面创建的随机数据:
# make some random example data to bin
np.random.seed(45)
x = np.arange(0,460)
y = 5+np.random.randn(460).cumsum()
plt.plot(x,y);
目标:
我想使用间隔序列来收集数据的统计信息(平均值、百分位数、等) - 但只能使用长间隔,即草图中的黄色间隔。
假设和说明:
长间隔的边缘永远不会重叠;换句话说,长间隔之间总是有一个短间隔。而且,第一个间隔总是很长的。
当前解决方案:
一种方法是在所有间隔上使用scipy.stats.binned_statistic,然后将结果切片以仅保留其他间隔(即[::2]),就像这样(对某些统计数据有很大帮助,例如np.percentile,正在阅读this SO answer 由@ali_m):
ave = scist.binned_statistic(x, y,
statistic = np.nanmean,
bins=bns)[0][::2]
这给了我想要的结果:
plt.plot(np.arange(0,5), ave);
问题:
是否有更 Pythonic 的方式来执行此操作(使用 Numpy、Scipy 或 Pandas 中的任何一个)?
【问题讨论】:
标签: python numpy scipy statistics binning