简体   繁体   English

Python:在 [X,Y] 坐标中查找每个 X 值的平均 Y 值

[英]Python: Find Average Y-Value for Each X-Value in [X,Y] Coordinates

Let's say I have a list of x,y coordinates like this:假设我有一个 x,y 坐标列表,如下所示:

coordinate_list = [(4,6),(2,5),(0,4),(-2,-2),(0,2),(0,0),(8,8),(8,11),(8,14)]

I want to find the average y-value associated with each x-value.我想找到与每个 x 值相关的平均 y 值。 So for instance, there's only one "2" x-value in the dataset, so the average y-value would be "5".例如,数据集中只有一个“2”x 值,因此平均 y 值将是“5”。 However, there are three 8's and the average y-value would be 11 [ (8+11+14) / 3 ].但是,有 3 个 8,平均 y 值为 11 [ (8+11+14) / 3 ]。

What would be the most efficient way to do this?最有效的方法是什么?

You can use pandas您可以使用pandas

coordinate_list = [(4,6),(2,5),(0,4),(-2,-2),(0,2),(0,0),(8,8),(8,11),(8,14)]
import pandas as pd
df = pd.DataFrame(coordinate_list)
df
df.groupby([0]).mean()
| 0 |  |  1  |
| --- | --- |
| -2 | -2 |
| 0 | 2 |
| 2 | 5 |
| 4 | 6 |
| 8 | 11 |
y_values_by_x = {}
for x, y in coordinate_list:
    y_values_by_x.setdefault(x, []).append(y)

average_y_by_x = {k: sum(v)/len(v) for k, v in y_values_by_x.items()}

Try the mean() function from statistics module with list comprehension尝试使用列表理解的统计模块中的 mean() function

from statistics import mean

x0_filter_value = 0   # can be any value of your choice for finding average
result = mean([x[1] for x in coordinate_list if x[0] == x0_filter_value])
print(result)

And to print means for all X[0] values:并打印所有 X[0] 值的方法:

 for i in set([x[0] for x in coordinate_list]):
      print (i,mean([x[1] for x in coordinate_list if x[0] == i]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM