gpt4 book ai didi

python - 取具有相同值的每个元素的平均值的最快方法?

转载 作者:太空宇宙 更新时间:2023-11-04 09:25:22 25 4
gpt4 key购买 nike

我不太确定如何提出这个问题。我几乎可以肯定以前有人问过这个问题,但我找不到。

我有一些数据,比如:

x = np.random.rand(100) * 0.0001
y = [round(i, 1) for i in np.random.rand(100)]

它们都是 100 个元素长。但是,y 只包含大约 10 个唯一元素。对于 y 中的每个唯一元素,我想取 x 中所有数字的平均值在同一个位置。

类似于:

averageX = []
for unique in set(y):
items = []
for i in y:
if i == unique: # For each copy of this number
items.append(x[i]) # take all the items in x at that index
averageX.append(mean(items)) # and take the average

执行此操作的最佳 pythonic 方法是什么?

最佳答案

如果你转换成 pandas,你可以利用 groupby

x = np.random.rand(100) * 0.0001
y = [round(i, 1) for i in np.random.rand(100)]

import pandas as pd
df=pd.DataFrame([x,y]).transpose().rename(columns={0:'x',1:'y'})
df.groupby(['y']).mean()

#Output:
#0.0 0.000019
#0.1 0.000046
#0.2 0.000051
#0.3 0.000049
#0.4 0.000031
#0.5 0.000043
#0.6 0.000051
#0.7 0.000049
#0.8 0.000044
#0.9 0.000053
#1.0 0.000034

关于python - 取具有相同值的每个元素的平均值的最快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57923114/

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