我有一个二维浮点数,看起来像这样(数据here):
如您所见,这些值不是唯一的,单个x值可以有多个y值。
我想通过获取x轴内给定间隔内的那些点的y值的平均值来产生单一平均曲线。
我可以在x轴上设置20个间隔,并在每个间隔上迭代,搜索x值位于其中的y值。这是MWE:
import numpy as np
# Define array with the data.
a = [[lots of floats][lots of floats]]
# Define intervals in x.
interv_x = np.linspace(14., 24., 20)
interv_y = []
for i, x in enumerate(interv_x):
if i < len(interv_x) - 1:
y_lst = []
# Search for points inside this interval.
for j, y_val in enumerate(a[1]):
if x <= a[0][j] < interv_x[i + 1]:
y_lst.append(y_val)
# Average the y values of all these points.
interv_y.append(np.average(y_lst))
# Plot results.
plt.scatter(a[0], a[1], c='b', s=10)
plt.scatter(interv_x[:-1], interv_y, c='r', s=50)
plt.show()
产生:
其中红点是平均值。
有没有办法用函数做到这一点?我愿意接受涉及numpy
和/或scipy
的解决方案。