gpt4 book ai didi

python - 使用 Python 连接 CSV 中的行

转载 作者:行者123 更新时间:2023-11-28 19:17:15 26 4
gpt4 key购买 nike

我有一个 CSV(~1.5m 行),格式如下:

id, tag1, tag2, name1, value1

有几行具有相同的id。如果一行具有相同的 id,它将具有相同的 tag1 和 tag2。所以,我想要做的是在行的末尾追加 name1, value1 这将是不同的。

例子:

Original:
id,tag1,tag2,name1,value1
12,orange,car,john,32
13,green,bike,george,23
12,orange,car,elen,21
Final:
id,tag1,tag2,name1,value1
12,orange,car,john,32,elen,21
13,green,bike,george,23

我能做到的唯一方法是使用 Python 中的暴力脚本。使用 id 的键创建一个字典,然后创建一个包含所有其他参数的列表。每次我找到一个已经在字典中的 id 时,我只是将字典值中的最后两个字段附加为一个列表。

但是,在这么大的文件中,这并不是最有效的方法。有没有其他方法可以做到这一点,也许是图书馆?

最佳答案

Kay 使用排序输入数据的建议可能看起来像这样:

with open('in.txt') as infile, open('out.txt', mode='w') as outfile:
# Prime the first line
line = infile.readline()
# When collating lines, running_line will look like:
# ['id,tag1,tag2', 'name1', 'value1', 'name2', 'value2', ...]
# Prime it with just the 'id,tag1,tag2' of the first line
running_line = [line[:-1].rsplit(',', 2)[0]]
while line:
curr_it12, name, value = line[:-1].rsplit(',', 2)
if running_line[0] == curr_it12:
# Current line's id/tag1/tag2 matches previous line's.
running_line.extend([name, value])
else:
# Current line's id/tag1/tag2 doesn't match. Output the previous...
outfile.write(','.join(running_line) + '\n')
# ...and start a new running_line
running_line = [curr_it12, name, value]
# Grab the next line
line = infile.readline()
# Flush the last line
outfile.write(','.join(running_line) + '\n')

关于python - 使用 Python 连接 CSV 中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32119253/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com