python - Python上的平均计算
问题描述
我有这个函数可以计算相同 x 的 y 值的平均值,但是当我有 (x +/- eps) 时它不起作用。
import numpy as np
import matplotlib.pyplot as plt
from uncertainties import ufloat
from uncertainties.umath import *
x = np.array([0, 0,1,1,2,2,2], float)
y = np.array([1, 2, 3,5,4, 4, 6.8], float)
def avg_group(x, y):
A, ind, counts = np.unique(x, return_index=True, return_counts=True)
B = y[ind]
for dup in A[counts>1]:
B[(A==dup)] = np.average(y[(x==dup)] )
return A, B
new_x, new_y = avg_group(x, y)
plt.plot(new_x,new_y,'o')
plt.show()
如何在 avg_average 中添加条件以获得 y 的平均值(对于 x+/- eps)?
解决方案
我不认为有这样做的内置功能。即使有,这个问题也有一点模棱两可。考虑这样的序列:
x = x1, x1+eps, x1 + 2eps...
x1
接近x1+eps
(即在 eps 内)但不接近x1+2eps
. x1+eps
都接近x1
和x1+2eps
。我们将哪些 x 视为“相同”?x1
和x1+eps
可以被视为相同,但x1+eps
和也可以x2+eps
。为了进一步讨论,我认为在这种情况下我们将有两个不同的 x 值:x1
和x1+2eps
。
假设上述情况,我们可以遍历 x 的排序副本,并且对于 x 的每个值,我们检查它是否与之前的值足够接近。如果是,我们将其与先前的值分组,否则创建一个新条目。
我扩展了您的代码以实现上述内容。
import numpy as np
import matplotlib.pyplot as plt
eps = 1e-5
x = np.array([0, 0,1,1,2,2,2], float)
y = np.array([1, 2, 3,5,4, 4, 6.8], float)
def avg_group(x, y):
# sort by x-vales
sorted_indices = np.argsort(x)
x = x[sorted_indices]
y = y[sorted_indices]
sum_and_count = [(x[0], y[0], 1)]
# we are maintaining a list of tupls of (x, sum of y, count of y)
for index, (current_x, current_y) in enumerate(zip(x[1:], y[1:]), 1):
# check if this x value is eps close to the previous x value
previous_x = x[index-1]
if current_x - previous_x <= eps:
# This entry belongs to the previous tuple
prev_tuple = sum_and_count[-1]
new_tuple = (prev_tuple[0], prev_tuple[1]+current_y, prev_tuple[2]+1)
sum_and_count[-1] = new_tuple
else:
# insert a new tuple
new_tuple = (current_x, current_y, 1)
sum_and_count.append(new_tuple)
x, sum_y, count_y = zip(*sum_and_count)
return np.asarray(x), np.asarray(sum_y) / np.asarray(count_y)
new_x, new_y = avg_group(x, y)
plt.plot(new_x,new_y,'o')
plt.show()
此处链接了一个 colab 笔记本(带有代码)。
让我知道这是否有帮助或者您有任何后续问题:)
推荐阅读
- sorting - 为什么 Lua 的 table.sort 方法对我的数据不起作用
- javascript - MDB 多选未正确显示
- python - 如何获取><之间的数字
- r - `v` 的最小日期使差异 `wv` 为正
- sql - 带有错误 GUID 的 Transact-SQL Select 语句结果
- amazon-web-services - aws cloudfront 签名的 url 和 mediapackage
- performance - 单独压缩每一行还是压缩整个文件更好?
- javascript - ReferenceError: openpgp 未定义
- java - HTTPS OpenStreetMap URL 无法通过 java 应用程序访问,而可通过浏览器和 IntelliJ“测试连接”访问
- java - Glassfish4:Waffle SSO Servlet 过滤器提供基本身份验证登录弹出窗口