Python:根据一个键列合并数据
Python: Combine data based on a key column
在同一个文本文件中包含 parent 和 child 记录的数据(两个 headers)。
Parent 是 department
,child 是 employees
,dno
是连接列。
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,这似乎有效。不确定这是否是最佳解决方案。
想知道是否有任何其他有效的ways/alternatives处理这种情况
使用 Python Standard Library - 2.6
.
考虑阅读第一部分并构建一个跟进词典,然后切换到第二部分并使用该词典。此外,考虑使用 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]])
在同一个文本文件中包含 parent 和 child 记录的数据(两个 headers)。
Parent 是 department
,child 是 employees
,dno
是连接列。
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,这似乎有效。不确定这是否是最佳解决方案。
想知道是否有任何其他有效的ways/alternatives处理这种情况
使用 Python Standard Library - 2.6
.
考虑阅读第一部分并构建一个跟进词典,然后切换到第二部分并使用该词典。此外,考虑使用 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]])