python合并了两个数据不一致的文件

python合并了两个数据不一致的文件,python,csv,combiners,Python,Csv,Combiners,现在我有两个文件:A和B。都是csv文件 csv A有一些数据: a b c 1 2 3 4 5 6 7 8 9 ..... b d 7 0 8 3 2 1 ..... a、b、c 1 2 3 4 5 6 7 8 9 ..... csv B有一些数据: a b c 1 2 3 4 5 6 7 8 9 ..... b d 7 0 8 3 2 1 ..... b-d 7 0 8 3 2 1 ..... 现在我想将两个csv文件A和B合并为一个新文件C,如下所示: a b c d 1 2 3

现在我有两个文件:A和B。都是csv文件

csv A有一些数据:

a b c 1 2 3 4 5 6 7 8 9 ..... b d 7 0 8 3 2 1 ..... a、b、c 1 2 3 4 5 6 7 8 9 ..... csv B有一些数据:

a b c 1 2 3 4 5 6 7 8 9 ..... b d 7 0 8 3 2 1 ..... b-d 7 0 8 3 2 1 ..... 现在我想将两个csv文件A和B合并为一个新文件C,如下所示:

a b c d 1 2 3 1 7 8 9 3 ...... def open_func(file_name): open_dict={} key_list=[] fd=csv.reader(open(file_name,'r')) j=1 for line in fd: data_len=len(line) if not j: try: for i in range(data_len): open_dict[key_list[i]].append(line[i]) except: #print line continue else: for i in range(data_len): key=line[i] key_list.append(key) for i in range(data_len): open_dict[key_list[data_len-i-1]]=[] j=0 continue return open_dict a、b、c、d 1 2 3 1 7 8 9 3 ...... 首先,我必须使用csv.reader读取文件,代码如下:

a b c d 1 2 3 1 7 8 9 3 ...... def open_func(file_name): open_dict={} key_list=[] fd=csv.reader(open(file_name,'r')) j=1 for line in fd: data_len=len(line) if not j: try: for i in range(data_len): open_dict[key_list[i]].append(line[i]) except: #print line continue else: for i in range(data_len): key=line[i] key_list.append(key) for i in range(data_len): open_dict[key_list[data_len-i-1]]=[] j=0 continue return open_dict def open_func(文件名): open_dict={} 键列表=[] fd=csv.reader(打开(文件名,'r')) j=1 对于fd中的行: 数据长度=长度(直线) 如果不是j: 尝试: 对于范围内的i(数据长度): 打开目录[键列表[i]]。追加(第[i]行) 除: #打印行 继续 其他: 对于范围内的i(数据长度): 键=行[i] 键列表。追加(键) 对于范围内的i(数据长度): 打开目录[键列表[数据列-i-1]=[] j=0 持续 返回打开的目录 我使用dict来读取它们,如果相等,我想使用组合键

但我不知道该怎么办


注意:数据超过一百万行。

我强烈建议您使用
pandas
来实现这一点,它为Python提供了高性能、易于使用的数据结构和数据分析工具。因此,您可以尝试使用它来处理大型数据

e、 g

或从csv读取文件:

f1 = pd.read_csv('1.csv',sep="\s+")
f2 = pd.read_csv('2.csv',sep="\s+")
您可以通过以下方式将其写入文件:

f.to_csv('out.csv', index=False)
out.csv:

a,b,c,d
1,2,3,1.0
4,5,6,
7,8,9,3.0
让这变得相当容易:

代码:

import pandas as pd

df1 = pd.read_csv('file1', sep='\s+')
df2 = pd.read_csv('file2', sep='\s+')

df = df1.merge(df2, on=['b'])
print(df)
   a  b  c  d
0  1  2  3  1
1  7  8  9  3
结果:

import pandas as pd

df1 = pd.read_csv('file1', sep='\s+')
df2 = pd.read_csv('file2', sep='\s+')

df = df1.merge(df2, on=['b'])
print(df)
   a  b  c  d
0  1  2  3  1
1  7  8  9  3

非常感谢,当我使用merge时,它显示:keyrerror'xxxx',我的代码是combine_pan=pand1.merge(pand2,how='left',on=equal_name),pand1和pand2从csv读取