我正在尝试执行以下操作:确定嵌套列表中是否存在“NA”值,如果存在,则将其替换为列表中其他元素之和的平均值。列表的元素应该是浮点数。例如:
[["1.2","3.1","0.2"],["44.0","NA","90.0"]]
应该返回
[[1.2, 3.1, 0.2], [44.0, 67.0, 90.0]]
下面的代码虽然冗长且多余,但可以正常工作:
def convert_data(data):
first = []
second = []
third = []
fourth = []
count = 0
for i in data:
for y in i:
if 'NA' not in i:
y = float(y)
first.append(y)
elif 'NA' in i:
a = i.index('NA')
second.append(y)
second[a] = 0
for q in second:
q = float(q)
third.append(q)
count+= q
length = len(third)
count = count/(length-1)
third[a] = count
fourth.extend([first,third])
return fourth
data = [["1.2","3.1","0.2"],["44.0","NA","90.0"]]
convert_data(data)
例如:
data = [["1.2","3.1","0.2"],["44.0","NA","90.0"]]
convert_data(data)
返回所需的输出:
[[1.2, 3.1, 0.2], [44.0, 67.0, 90.0]]
但是如果“NA”在第一个列表中,例如
data = [["1.2","NA","0.2"],["44.0","67.00","90.0"]]
然后它没有。有人可以解释如何解决这个问题吗?