基于第一列合并行的 Python 脚本

标签 python csv sorting merge

我已经看到了很多关于此问题的问题/答案,但我所看到的都没有解决我的问题,因此任何帮助将不胜感激。

我有一个非常大的 CSV 文件,其中有一些重复的列条目,但我想要一个脚本来根据第一列匹配和合并行。 (我不想使用 pandas。我使用的是 Python 2.7。文件中没有 CSV header )

这是输入:

2144, 2016, 505, 20005, 2007, PP, GPP, DAC, UNSW 
8432, 2015, 505, 20005, 2041, LL, GLO, X2, UNSW
0055, 0.00, 0.00, 2014, 2017
2144, 0.00, 0.00, 2016, 959
8432, 22.9, 0.00, 2015, 2018 
0055, 2014, 505, 20004, 2037, LL, GLO, X2, QAL

想要的输出:

2144, 0.00, 0.00, 2016, 959, 2016, 505, 20005, 2007, PP, GPP, DAC, UNSW  
0055, 0.00, 0.00, 2014, 2017, 2014, 505, 20004, 2037, LL, GLO, X2, QAL   
8432, 22.9, 0.00, 2015, 2018, 2015, 505, 20005, 2041, LL, GLO, X2, UNSW

我已经尝试过:

reader = csv.reader(open('input.csv))
result = {}

for row in reader:
    idx = row[0]
    values = row[1:]
    if idx in result:
        result[idx] = [result[idx][i] or v for i, v in enumerate(values)]
    else:
        result[idx] = values

这用于搜索重复项:

with open('1.csv','r') as in_file, open('2.csv','w') as out_file:
    seen = set() # set for fast O(1) amortized lookup
    for line in in_file:
        if line in seen: continue

但这些并没有帮助我 - 我迷路了

任何帮助都会很棒。

谢谢

最佳答案

尝试使用字典,将第一列的值作为键。我会这样做:

with open('myfile.csv') as csvfile:
    reader = list(csv.reader(csvfile, skipinitialspace=True))  # remove the spaces after the commas
    result = {}  # or collections.OrderedDict() if the output order is important
    for row in reader:
        if row[0] in result:
            result[row[0]].extend(row[1:])  # do not include the key again
        else:
            result[row[0]] = row

    # result.values() returns your wanted output, for example :
    for row in result.values():
        print(', '.join(row))

关于基于第一列合并行的 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48777130/

相关文章:

c++ - 对指针列表进行排序 C++ - 没有匹配的函数错误

c# - 使用 C# 将数据表中的字符串项排序为 int

c - 使用 struct 与 pthread 进行合并排序

java - java 是否有等同于 python __call__ 的东西?

python - 在 Django 中创建自定义字段查找

ruby-on-rails - 从复杂的 Rails 查询导出到 CSV

python - 在 python 中将列表导出为 csv 文件并获取 UnicodeEncodeError

python - 在 Python 的单词列表中查找三个单词

python - 使用Python标准库显示函数状态

python - 在 Python 中将嵌套的 JSON 转换为 CSV 文件