Python:基于键列合并数据

问题描述 投票:0回答:1

具有在同一文本文件(两个标题)中包含父记录和子记录的数据。父级是department,子级是employeesdno是联接列。

dno,dname,loc
10,FIN,USA
20,HR,EUR
30,SEC,AUS
empno,ename,sal,dno
2100,AMY,1001,10
2200,JENNY,2001,10
3100,RINI,3001,20
4100,EMP4,4001,30
4200,EMP5,5001,30
4300,EMP6,6001,30

想要通过dno合并两个数据并创建如下所示的输出:

empno,ename,sal,dno,dname,loc
2100,AMY,1001,10,FIN,USA
2200,JENNY,2001,10,FIN,USA
3100,RINI,3001,20,HR,EUR
4100,EMP4,4001,30,SEC,AUS
4200,EMP5,5001,30,SEC,AUS
4300,EMP6,6001,30,SEC,AUS

Python version - 2.6

尝试过以下解决方案:

dept_lst = []
emp_lst = []

with open(efile,'rb') as e_file:
    reader = csv.reader(e_file,delimiter=",")
    for row in reader:
        if ((row[0] != 'dno' and row[0] != 'dname' ) or 
            (row[0] != 'empno' and row[0] != 'ename')):
            if len(row) == 3:
                dept_lst.append(row)
            elif len(row) == 4:
                emp_lst.append(row)

result = [ e + [d[1],d[2]] for e in emp_lst for d in dept_lst if e[3] == d[0]]

for line in result:
    print ",".join(line)

问题:原始数据超过1GB,这似乎可以正常工作。不确定这是否是最佳解决方案。

想知道是否还有其他有效的方法/替代方案来处理这种情况使用Python Standard Library - 2.6

python python-2.6
1个回答
1
投票

考虑阅读第一部分并建立后续词典,然后切换到第二部分并使用该词典。另外,考虑使用CSV编写器一次写入已处理的行,而不是将其保存为列表。

dno = {}
# Why do you open the file in the binary mode?
with open("efile.csv", "r") as e_file,\
     open("ofile.csv", "w") as o_file:
    reader = csv.reader(e_file)
    next(reader) # Skip the header
    for row in reader:
        if row[0] == 'empno':
            break # The second part begins
        dno[row[0]] = row[1:]
    writer = csv.writer(o_file)
    for row in reader:
        writer.writerow(row + dno[row[3]])
© www.soinside.com 2019 - 2024. All rights reserved.