python - (python) 如果条件成立,则在连续行中添加元素

标签 python arrays sorting rows

我有一个包含“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/

相关文章:

使用 dc.js 对条形图中的条形进行排序

arrays - 按每个结构体的成员对结构体数组进行排序

python - 在保持某些变量不变的情况下最小化函数

python - 如何在 Python-telegram-bot 中使用 Jobqueue

Python 等同于 R poly() 函数?

python - 如何在 Keras 中的每批之后更新训练日志输出?

java - firestore 中的数组对象返回 null,而其他字段则不返回 null

php - foreach 循环将数据库中的多个单选按钮填充到 php 字符串中

sorting - Tapestry 网格默认排序

java - 在 jython 中为 java interop 创建数组数组