我有一组成对的 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/