我有一份清单清单:
list_of_lists = []
list_1 = [-1, 0.67, 0.23, 0.11]
list_2 = [-1]
list_3 = [0.54, 0.24, -1]
list_4 = [0.2, 0.85, 0.8, 0.1, 0.9]
list_of_lists.append(list_1)
list_of_lists.append(list_2)
list_of_lists.append(list_3)
list_of_lists.append(list_4)
这个职位很有意义。我想返回一个包含每个位置平均值的列表,不包括-1。也就是说,我想:
[(0.54+0.2)/2, (0.67+0.24+0.85)/3, (0.23+0.8)/2, (0.11+0.1)/2, 0.9/1]
实际上是:
[0.37, 0.5866666666666667, 0.515, 0.10500000000000001, 0.9]
我怎样才能以pythonic的方式做到这一点?
编辑:
我正在使用Python 2.7,我不是在寻找每个列表的平均值;相反,我正在寻找“排名0的所有列表元素(不包括-1)”的平均值,以及“位置1的所有列表元素(不包括-1)”的平均值等。
我的原因:
[(0.54+0.2)/2, (0.67+0.24+0.85)/3, (0.23+0.8)/2, (0.11+0.1)/2, 0.9/1]
是位置0的值是-1,-1,0.54和0.2,我想排除-1;位置1有0.67,0.24和0.85;位置3有0.23,-1和0.8等
答案 0 :(得分:2)
没有第三方库的解决方案:
from itertools import zip_longest
from statistics import mean
def f(lst):
return [mean(x for x in t if x != -1) for t in zip_longest(*lst, fillvalue=-1)]
>>> f(list_of_lists)
[0.37, 0.5866666666666667, 0.515, 0.10500000000000001, 0.9]
它使用itertools.zip_longest
并fillvalue
设置为-1
来“转置”列表并将缺失值设置为-1
(将在下一步中忽略)。然后,生成器表达式和statistics.mean
用于过滤掉-1
并获得平均值。
答案 1 :(得分:1)
这是一个基于矢量化numpy
的解决方案。
import numpy as np
a = [[-1, 0.67, 0.23, 0.11],
[-1],
[0.54, 0.24, -1],
[0.2, 0.85, 0.8, 0.1, 0.9]]
# first create non-jagged numpy array
b = -np.ones([len(a), max(map(len, a))])
for i, j in enumerate(a):
b[i][0:len(j)] = j
# count negatives per column (for use later)
neg_count = [np.sum(b[:, i]==-1) for i in range(b.shape[1])]
# set negatives to 0
b[b==-1] = 0
# calculate means
means = [np.sum(b[:, i])/(b.shape[0]-neg_count[i]) \
if (b.shape[0]-neg_count[i]) != 0 else 0 \
for i in range(b.shape[1])]
# [0.37,
# 0.58666666666666667,
# 0.51500000000000001,
# 0.10500000000000001,
# 0.90000000000000002]
答案 2 :(得分:1)
您可以使用pandas模块进行处理。代码是这样的:
import numpy as np
import pandas as pd
list_1 = [-1, 0.67, 0.23, 0.11,np.nan]
list_2 = [-1,np.nan,np.nan,np.nan,np.nan]
list_3 = [0.54, 0.24, -1,np.nan,np.nan]
list_4 = [0.2, 0.85, 0.8, 0.1, 0.9]
df=pd.DataFrame({"list_1":list_1,"list_2":list_2,"list_3":list_3,"list_4":list_4})
df=df.replace(-1,np.nan)
print(list(df.mean(axis=1)))