我是 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
的数据包含不同的贸易值(value),但我想删除这些行并且只包含 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
关于python - 如何通过python在csv文件中添加反向重复列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29705948/