![](/img/trans.png)
[英]Python - Fastest way to find the average value over entire dict each time it gets modified?
[英]Fastest way of taking the average of each element which has the same value?
我不太确定如何提出这个问题。 我几乎可以肯定会问过这个问题,但是我找不到。
我有一些数据,例如:
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方法是什么?
所以... x
是一些数据, y
是将x
每个索引映射到一个类别的排序类别映射,您需要每个类别的平均值吗?
import collections
import random
x = [random.randint(0, 100) for i in range(100)] # data
y = [random.randint(0, 10) for i in range(100)] # categories
data_per_category = collections.defaultdict(list)
for category, datum in zip(y, x): # iterate in parallel over both y and x
data_per_category[category].append(datum)
for category, data in data_per_category.items():
print(category, sum(data) / len(data))
打印输出(例如)
9 51.2
5 49.0
8 56.75
1 48.166666666666664
7 45.0
0 38.42857142857143
3 50.333333333333336
4 43.7
6 45.4
10 53.0
2 44.583333333333336
如果您转换为熊猫,则可以利用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
我不确定效率,但是您可以使用遮罩:
means = {}
for i in y:
if i not in means:
means[i] = x[y == i].mean()
另一种可能更有效的方法是排序:
data = np.stack((x, y), axis=0)
data = data[np.lexsort(data), :]
现在的分裂是连续的,所以你可以做简单的东西
breaks = np.flatnonzero(np.diff(data[:, 1]))
start = np.concatenate(([0], breaks))
end = np.concatenate((breaks, [data.shape[0]]))
means = np.add.reduceat(data[:, 0], start) / (end - start)
在排序的数据,一个非零差异在y
表示的一个新的值y
。 您可以使用它来计算x
中具有相同y
值的每个段的起点和终点的索引。 段的总和由起始索引之间的reduceat
给出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.