簡體   English   中英

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

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM