Rk_*_*_23 12 python python-2.7 python-3.x
我目前有两组数据文件,如下所示:
档案1:
test1 ba ab cd dh gf
test2 fa ab cd dh gf
test3 rt ty er wq ee
test4 er rt sf sd sa
Run Code Online (Sandbox Code Playgroud)
在文件2中:
test1 123 344 123
test1 234 567 787
test1 221 344 566
test3 456 121 677
Run Code Online (Sandbox Code Playgroud)
我想基于第一列中的数学行组合文件(以便"测试"匹配)
像这样:
test1 ba ab cd dh gf 123 344 123
test1 ba ab cd dh gf 234 567 787
test1 ba ab cd dh gf 221 344 566
test3 rt ty er wq ee 456 121 677
Run Code Online (Sandbox Code Playgroud)
我有这个代码
def combineFiles(file1,file2,outfile):
def read_file(file):
data = {}
for line in csv.reader(file):
data[line[0]] = line[1:]
return data
with open(file1, 'r') as f1, open(file2, 'r') as f2:
data1 = read_file(f1)
data2 = read_file(f2)
with open(outfile, 'w') as out:
wtr= csv.writer(out)
for key in data1.keys():
try:
wtr.writerow(((key), ','.join(data1[key]), ','.join(data2[key])))
except KeyError:
pass
Run Code Online (Sandbox Code Playgroud)
但是输出最终看起来像这样:
test1 ba ab cd dh gf 123 344 123
test3 er rt sf sd sa 456 121 677
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮助我如何输出,以便test1可以打印三次?
非常感激
您可能想尝试一下Pandas库; 它使这样的案例变得容易:
>>> import pandas as pd
>>> pd.merge(df1, df2, on='testnum', how='inner')
testnum 1_x 2_x 3_x 4 5 1_y 2_y 3_y
0 test1 ba ab cd dh gf 123 344 123
1 test1 ba ab cd dh gf 234 567 787
2 test1 ba ab cd dh gf 221 344 566
3 test3 rt ty er wq ee 456 121 677
Run Code Online (Sandbox Code Playgroud)
这假设测试列名为"testnum".
>>> df1
testnum 1 2 3 4 5
0 test1 ba ab cd dh gf
1 test2 fa ab cd dh gf
2 test3 rt ty er wq ee
3 test4 er rt sf sd sa
>>> df2
testnum 1 2 3
0 test1 123 344 123
1 test1 234 567 787
2 test1 221 344 566
3 test3 456 121 677
Run Code Online (Sandbox Code Playgroud)
你读过这些pd.read_csv().
虽然我推荐Brad Solomon 的方法,因为它非常简洁,但您只需要对代码进行一些小的更改。
由于您的第二个文件具有“最终决定权”,因此您只需为第一个文件创建一个字典即可。然后,您可以在从第二个文件读取时写入输出文件,data1同时从字典中获取值:
with open(file1, 'r') as f1, open(file2, 'r') as f2:
data1 = read_file(f1)
with open(outfile, 'w') as out:
wtr = csv.writer(out, delimiter=' ')
for line in csv.reader(f2, delimiter=' '):
# only write if there is a corresponding line in file1
if line[0] in data1:
# as you write, get the corresponding file1 data
wtr.writerow(line[0:] + data1[line[0]] + line[1:])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
257 次 |
| 最近记录: |