Skip to main content
 首页 » 编程设计

python之合并 2 个没有标题的表(有公共(public)列)

2025年05月04日29飞鱼

我有 2 个表,说:

table1 = 101 1 2 3 
         201 4 5 6 
         301 7 8 9 
 
table2 = 10 11 101 12 
         13 14 201 15 
         16 17 301 18 

很明显table1 column1和table2 column 3是公共(public)列。我想使用 pd.join 加入这 2 个表,但问题是我的表没有 header。那么我该如何使用 pandas 来做到这一点呢?

编辑

我正在使用 pd.read_csv 来读取表格。我的表格是文本文件。

outputtable = 101 1 2 3 10 11 12 
              201 4 5 6 13 14 15 
              301 7 8 9 16 17 18 

我想将 outputtable 导出为文本文件。

请您参考如下方法:

我将索引设置为您要合并的序号列,然后合并,重命名索引名称,因为之后您需要重置索引:

In [121]: 
import io 
import pandas as pd 
# read in data, you can ignore the io.StringIO bit and replace with your paths 
t="""101 1 2 3 
         201 4 5 6 
         301 7 8 9""" 
table1 = pd.read_csv(io.StringIO(t), sep='\s+', header=None) 
 
t1="""10 11 101 12 
         13 14 201 15 
         16 17 301 18""" 
table2 = pd.read_csv(io.StringIO(t1), sep='\s+', header=None) 
​# merge the tables after setting index 
merged = table1.set_index(0).merge(table2.set_index(2), left_index=True, right_index=True) 
# rename the index name so it doesn't bork complaining about column 0 existing already 
merged.index.name = 'index' 
merged = merged.reset_index() 
merged 
 
Out[121]: 
   index  1_x  2  3_x   0  1_y  3_y 
0    101    1  2    3  10   11   12 
1    201    4  5    6  13   14   15 
2    301    7  8    9  16   17   18 

您现在可以根据需要导出 df 并传递 header=False:

In [124]: 
merged.to_csv(header=False, index=False) 
 
Out[124]: 
'101,1,2,3,10,11,12\n201,4,5,6,13,14,15\n301,7,8,9,16,17,18\n'