首页 > 解决方案 > 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)?

标签: pythonfunctionnumpymatplotlib

解决方案


我不认为有这样做的内置功能。即使有,这个问题也有一点模棱两可。考虑这样的序列:

x = x1, x1+eps, x1 + 2eps...

x1接近x1+eps(即在 eps 内)但不接近x1+2eps. x1+eps都接近x1x1+2eps。我们将哪些 x 视为“相同”?x1x1+eps可以被视为相同,但x1+eps和也可以x2+eps。为了进一步讨论,我认为在这种情况下我们将有两个不同的 x 值:x1x1+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 笔记本(带有代码)。

让我知道这是否有帮助或者您有任何后续问题:)


推荐阅读