Python bin 成对的交错数组

标签 python arrays numpy

我有一组成对的 numpy 数组。一对中的每个数组长度相同,但不同对中的数组长度不同。该集合中一对数组的示例是:

Time: [5,8,12,17,100,121,136,156,200]
Score: [3,4,5,-10,-90,-80,-70,-40,10]

另一对是:

Time: [6,7,9,15,199]
Score: [5,6,7,-11,-130]

我需要根据时间对所有这些对取平均值(或执行合并)。也就是说,时间应该被分成 10 个间隔,并且每个间隔的相应分数需要被平均。

因此,对于上述 2 对,我想要以下结果:

Time: [1-10,11-20,21-30,31-40,41-50,...,191-200]
Score: [(3+4+5+6+7)/5, (5-10-11)/2, ...]

我该怎么做?有没有比单独装箱然后取平均值更简单的方法呢?如何根据另一个数组的 bin 对一个数组进行 bin?即,对于一对单独的数组,我如何将时间数组以 10 为间隔进行分箱,然后使用此结果以一致的方式对相应的分数数组进行分箱?

最佳答案

您可以使用 scipy.stats.binned_statistic。这是直方图函数的推广。直方图将空间划分为 bin,并返回每个 bin 中点数的 count。此函数允许计算每个 bin 中的值(或值集)的总和、平均值、中位数或其他统计数据

from scipy import stats
import numpy as np

T1 = [5,8,12,17,100,121,136,156,200]
S1 = [3,4,5,-10,-90,-80,-70,-40,10]

T2 = [6,7,9,15,199]
S2 = [5,6,7,-11,-130]

# Merging all Times and Scores in order
Time = T1 + T2
Score = S1 + S2

output = stats.binned_statistic(Time, Score, statistic='mean',range=(0,200), bins=20)

averages = output[0]

# For empty bins, it generates NaN, we can replace them with 0
print( np.nan_to_num(averages, 0) )

# Output of this code: 
# [  5.          -5.33333333   0.           0.           0.
#    0.           0.           0.           0.           0.
#  -90.           0.         -80.         -70.           0.
#  -40.           0.           0.           0.         -60.        ]

有关更多信息,请关注 this link .

关于Python bin 成对的交错数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59473736/

相关文章:

arrays - 数组向量的内存布局是什么?

Python pandas/numpy 将 1 填充到具有值的单元格,并将 0 填充到 nan 的单元格

python - 一个集合的 K 个不同的 M 大小子集的确定性 python 生成器

python - 使用 python、numpy 和 matplotlib 绘制蒙面曲面图

python - 奇怪的 ~150ms 启动惩罚使用 python setuptools

python - 我可以使用 self 访问类变量吗?

python - 以最聪明的 pythonic 方式将用户返回到 flask 中的引荐来源网址

python - CP 求解器可以在特定点初始化吗?

javascript - 对空数组的变量使用 OR 运算的目的是什么?

python - 如何在 Python 中生成具有给定均值、方差、偏度和峰度的分布?