[英]Calculating Mean of arrays with different lengths
當它們的長度可能不同時,是否可以計算多個 arrays 的平均值? 我正在使用 numpy。假設我有:
numpy.array([[1, 2, 3, 4, 8], [3, 4, 5, 6, 0]])
numpy.array([[5, 6, 7, 8, 7, 8], [7, 8, 9, 10, 11, 12]])
numpy.array([[1, 2, 3, 4], [5, 6, 7, 8]])
現在我想計算均值,但忽略“缺失”的元素(當然,我不能只計算 append 個零,因為這會弄亂均值)
有沒有辦法在不遍歷 arrays 的情況下做到這一點?
附言。 這些 arrays 都是二維的,但該數組的坐標數量始終相同。 即第一個數組是5和5,第二個是6和6,第三個是4和4。
一個例子:
np.array([[1, 2], [3, 4]])
np.array([[1, 2, 3], [3, 4, 5]])
np.array([[7], [8]])
這個必須給
(1+1+7)/3 (2+2)/2 3/1
(3+3+8)/3 (4+4)/2 5/1
並以圖形方式:
[1, 2] [1, 2, 3] [7]
[3, 4] [3, 4, 5] [8]
現在想象一下,這些 2-D arrays 被放置在彼此之上,坐標重疊有助於該坐標的平均值。
numpy.ma.mean允許您計算非屏蔽數組元素的平均值。 但是,要使用numpy.ma.mean
,您必須首先將三個 numpy arrays 組合成一個掩碼數組:
import numpy as np
x = np.array([[1, 2], [3, 4]])
y = np.array([[1, 2, 3], [3, 4, 5]])
z = np.array([[7], [8]])
arr = np.ma.empty((2,3,3))
arr.mask = True
arr[:x.shape[0],:x.shape[1],0] = x
arr[:y.shape[0],:y.shape[1],1] = y
arr[:z.shape[0],:z.shape[1],2] = z
print(arr.mean(axis = 2))
產量
[[3.0 2.0 3.0]
[4.66666666667 4.0 5.0]]
我經常需要它來繪制不同長度的性能曲線的平均值。
用簡單的 function 解決了它(基於@unutbu 的回答):
def tolerant_mean(arrs):
lens = [len(i) for i in arrs]
arr = np.ma.empty((np.max(lens),len(arrs)))
arr.mask = True
for idx, l in enumerate(arrs):
arr[:len(l),idx] = l
return arr.mean(axis = -1), arr.std(axis=-1)
y, error = tolerant_mean(list_of_ys_diff_len)
ax.plot(np.arange(len(y))+1, y, color='green')
因此,將 function 應用於上面繪制的曲線列表會產生以下結果:
下面的 function 也可以通過添加不同長度的 arrays 列來工作:
def avgNestedLists(nested_vals):
"""
Averages a 2-D array and returns a 1-D array of all of the columns
averaged together, regardless of their dimensions.
"""
output = []
maximum = 0
for lst in nested_vals:
if len(lst) > maximum:
maximum = len(lst)
for index in range(maximum): # Go through each index of longest list
temp = []
for lst in nested_vals: # Go through each list
if index < len(lst): # If not an index error
temp.append(lst[index])
output.append(np.nanmean(temp))
return output
從你的第一個例子開始:
avgNestedLists([[1, 2, 3, 4, 8], [5, 6, 7, 8, 7, 8], [1, 2, 3, 4]])
輸出:
[2.3333333333333335,
3.3333333333333335,
4.333333333333333,
5.333333333333333,
7.5,
8.0]
一開始沒有使用 np.amax(nested_lst) 或 np.max(nested_lst) 來查找最大值的原因是,如果嵌套列表的大小不同,它將返回一個數組。
OP,我知道你在尋找一個非迭代的內置解決方案,但下面實際上只需要 3 行(如果你結合transpose
和means
則為 2 行,但它會變得混亂):
arrays = [
np.array([1,2], [3,4]),
np.array([1,2,3], [3,4,5]),
np.array([7], [8])
]
mean = lambda x: sum(x)/float(len(x))
transpose = [[item[i] for item in arrays] for i in range(len(arrays[0]))]
means = [[mean(j[i] for j in t if i < len(j)) for i in range(len(max(t, key = len)))] for t in transpose]
輸出:
>>>means
[[3.0, 2.0, 3.0], [4.666666666666667, 4.0, 5.0]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.