gpt4 book ai didi

python 3.6。获取所有相同 X 坐标的平均 Y

转载 作者:太空宇宙 更新时间:2023-11-03 13:08:10 25 4
gpt4 key购买 nike

我有一个如下所示的坐标列表:

my_list = [[1, 1], [1, 3], [1, 5], [2, 1], [2, 3]]

正如我们所见,前三个坐标的 X 值相同,但 Y 不同,另外两个坐标的情况相同。我想制作新的列表,看起来像这样:

new_list = [[1, 3], [2, 2]]

其中 y1 = 3 = (1+3+5)/3y2 = 2 = (1+3)/2。我已经编写了下面的代码,但运行缓慢。

我使用数十万个坐标,所以问题是:如何让这段代码运行得更快?是否有任何优化或特殊的开源库可以加速我的代码?

提前谢谢你。

x_mass = []

for m in mass:
x_mass.append(m[0])

set_x_mass = set(x_mass)
list_x_mass = list(set_x_mass)

performance_points = []

def function(i):
unique_x_mass = []
for m in mass:
if m[0] == i:
unique_x_mass.append(m)

summ_y = 0
for m in unique_x_mass:
summ_y += m[1]
point = [float(m[0]), float(summ_y/len(unique_x_mass))]
performance_points.append(point)
return performance_points

for x in list_x_mass:
function(x)

最佳答案

创建DataFrame并聚合mean:

L = [[1, 1], [1, 3], [1, 5], [2, 1], [2, 3]]

L1 = pd.DataFrame(L).groupby(0, as_index=False)[1].mean().values.tolist()
print (L1)
[[1, 3], [2, 2]]

关于 python 3.6。获取所有相同 X 坐标的平均 Y,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51258954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com