3

假设我有一个列表数组

B = [[1,2,3],[1,2,3,4],[1,2]]

我想计算列中列表中元素的平均值。我该怎么做呢?

IE

如何获得等于最长列表的最终平均值数组:

[(1+1+1)/3,(2+2+2)/3,(3+3)/2,4/1] = [1,2,3,4]

我试过了:

final_array = np.array([mean(a) for a in zip(*(B))])

但这给了我一个数组,只要我的最短列表。这是口罩派上用场了吗?如果一系列列表让您感到畏缩,我深表歉意,我仍在习惯 Python。

4

6 回答 6

6

您可以使用熊猫的 DataFrame 来实现。

from pandas import DataFrame

B = [[1,2,3],[1,2,3,4],[1,2]]
df = DataFrame(B)
df.mean(axis=0)
""""
df
   0  1   2   3
0  1  2   3 NaN
1  1  2   3   4
2  1  2 NaN NaN

df.mean(axis=0)
0    1
1    2
2    3
3    4
"""
于 2013-06-11T12:49:25.733 回答
4

您需要用一些哨兵值(我使用 NaN)填充您的列表,然后使用该哨兵创建一个掩码数组。一旦有了掩码数组,就可以毫无问题地计算平均值。

>>> import numpy as np
>>> B = [[1,2,3],[1,2,3,4],[1,2]]
>>> 
>>> maxlen = max(len(x) for x in B)
>>> C = np.array([l+[np.nan]*(maxlen-len(l)) for l in B])
>>> C
array([[  1.,   2.,   3.,  nan],
       [  1.,   2.,   3.,   4.],
       [  1.,   2.,  nan,  nan]])
>>> dat = np.ma.fix_invalid(C)
>>> np.mean(dat,axis=0)
masked_array(data = [1.0 2.0 3.0 4.0],
             mask = [False False False False],
       fill_value = 1e+20)
于 2013-06-11T12:40:27.497 回答
1

另一种方法,使用cmpizip_longest

from itertools import izip_longest
[float(sum(col)) / sum(cmp(x,0) for x in col) for col in izip_longest(*B, fillvalue=0)]

这假设您的价值观是积极的。

于 2013-06-11T13:11:23.423 回答
1

使用itertools.izip_longestitertools.takewhile

>>> from itertools import takewhile, izip_longest
def means(lis):
    fill = object()
    for item in izip_longest(*lis,fillvalue = fill):
        vals = list(takewhile( lambda x : x!=fill , item))
        yield sum(vals)/float(len(vals))
...         
>>> lis = [[1,2,3],[1,2,3,4],[1,2]]
>>> lis.sort( key = len, reverse = True) #reverse sort the list based on length of items
>>> list(means(lis))
[1.0, 2.0, 3.0, 4.0]
于 2013-06-11T12:45:17.883 回答
0
B = [[1,2,3],[1,2,3,4],[1,2]]
data = {}
max_len = 0

for alist in B:
    length = len(alist)
    max_len = length if (length > max_len) else max_len

    for i in range(length):
        data.setdefault(i, []).append(alist[i])


results = []

for i in range(max_len):
    vals = data[i]
    results.append(sum(vals) / len(vals) )

print results

--output:--
[1, 2, 3, 4]
于 2013-06-11T12:49:00.183 回答
0

你可以在没有任何外部库的情况下做到这一点:

B = [[1,2,3],[1,2,3,4],[1,2]]
#compute max length of sub list
maxLen = max([len(x) for x in B])
#new list with number of empty lists equals to number of columns
transList = [[] for i in range(maxLen)]
#transforming list to new structure
for row in B:
    for col in row:
        transList[col-1].append(col)
#transList = [[1, 1, 1], [2, 2, 2], [3, 3], [4]] from now one its simple to get mean of the elements ;)
meanB = [float(sum(i))/len(i) for i in transList]
于 2013-06-11T13:05:52.597 回答