我有一个包含“N”行和“3”列的列表。如果连续行的前两个元素相同,那么我想添加第三列中的元素并返回带有添加的“第三列”值的单行。
例如
120.638000 -21.541700 0.3
120.638000 -21.541700 0.8
121.331001 -21.795500 0.5
120.688004 -21.587400 0.1
120.688004 -21.587400 0.5
120.688004 -21.587400 0.9
121.525002 -21.504200 0.9
至
120.638000 -21.541700 1.1 (add third column of row 1 and 2)
121.331001 -21.795500 0.5
120.688004 -21.587400 1.5 (sum(0.1,0.5,0.9))
121.525002 -21.504200 0.9
对于在 python 中实现这个有什么建议吗?
最佳答案
您可以使用csvreader
读取数据,然后您可以使用defaultdict根据第1,2列中的相同元组来总结第3列:
from collections import defaultdict
from csv import csvreader
result = defaultdict(float)
with open("<datafile>") as f:
data = csvreader(f, delimiter='\t')
for a,b,c in data:
result[(a,b)] += float(c)
for (a,b),c in result.items():
print(a, b, c)
这不一定以与字典未排序相同的顺序出现。
关于python - (python) 如果条件成立,则在连续行中添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29981651/