我有一长串列表,其内容类似于
List = [['Time', 0, 1, 2, 3, None, None], ['Position',0, 0, 1, 2, None, None], ['Weight',1, 1, 1, 2, None, None],['Time', 0, 1, 2, 3, 4, 5], ['Position',0, 2, 3, 4, 4, 3], ['Weight'], [1, 1, 2, 1, 2, 3]]
当导出到csv时看起来像
Time, 0, 1, 2, 3, 4, 5,
Position, 0, 0, 1, 2, None, None,
Weight, 1, 1, 1, 2, None, None,
Time, 0, 1, 2, 3, 4, 5,
Position, 0, 2, 3, 4, 4, 3,
Weight, 1, 1, 2, 1, 1, 3,
现在,我想在末尾附加三行,如下所示。
Time, 0, 1, 2, 3, 4, 5,
Total Position, 0, 2, 4, 6, 4, 3,
Total Weight, 2, 2, 3, 3, 1, 3,
我该怎么做?我面临的问题是
答案 0 :(得分:0)
import numpy as np #use numpy to sum row
def replace_none(line): #change None into 0
def test(elem):
return elem if elem is not None else 0
return np.array([test(elem) for elem in line])
def Total(list_,key):
line=np.zeros(len(list_[0])-1)
for l in list_:
if l[0]==key: # collect the right lines
line += replace_none(l[1:]) #sum
return ['Total '+key,*line]
List.append(Total(List,'Position'))
List.append(Total(List,'Weight'))