Skip to main content
 首页 » 编程设计

python之如何通过python为csv文件中的反向重复列添加值

2024年10月25日12txw1958

我是 Python 新手,我的数据有问题。我有一个包含 3 列的 csv 文件。第一列和第二列是国家 ISO 代码,第三列是这些国家之间的贸易值。 例如:

col1  col2 col3 
USA  FRA  1500* 
USA  AUS  2000 
FRA  GBR  1700   
FRA  USA  2000* 
AUS  FRA  3000 
GBR  DEU  4000 

如您所见,数据包含 USA FRA 和 FRA USA 的不同贸易值,但我想摆脱这些行,只有 USA FRA 并且该值将是它们 2 个值的平均值 ((1500+2000)/2) 意思是: 最后,我想将结果保存到一个 csv 文件中,该文件只重复一次配对交易链接,并且该值是第一个 csv 文件中值的平均值。像这样:

col1 col2 col3 
USA  FRA  1750 
USA  AUS  2000 
FRA  GBR  1700 
AUS  FRA  3000 
GBR  DEU  4000 

谢谢

请您参考如下方法:

这里有一些可以帮助您入门的东西。我会把输入解析留给你。

from collections import defaultdict 
dd = defaultdict(lambda: [])  # default an array for the dictionary value 
 
input = [  # TODO: populate input from csv 
    [ 'USA', 'FRA', 1500 ], 
    [ 'FRA', 'USA', 2000 ] 
] 
 
def make_key(v1, v2):  # sort the countries to find the keys 
    return ''.join(sorted((v1, v2))) 
 
for row in input: 
    key = make_key(row[0], row[1]) 
    dd[key].append(row[2])  # append the value to the array 
 
 
for k, v in dd.iteritems(): # TODO: write results to file 
    print(k, sum(v) / 2)  # print average