Python 通过编程在两个表上进行自然连接

Python 通过编程在两个表上进行自然连接,python,Python,我有两个包含数据的表(实际上是列表列表列表),我希望通过编程方式在这两个表之间进行自然连接(没有SQL,只是在代码中) 如果我只想在索引[0]处的一个公共列上进行连接,我可以这样做: for each row1 in table1: for each row2 in tabl2: if row1[0] == row2[0]: // then this needs to join newRow = row1 + row2 // pseudo-code bu

我有两个包含数据的表(实际上是列表列表列表),我希望通过编程方式在这两个表之间进行自然连接(没有SQL,只是在代码中)

如果我只想在索引[0]处的一个公共列上进行连接,我可以这样做:

for each row1 in table1:
   for each row2 in tabl2:
      if row1[0] == row2[0]:   // then this needs to join
         newRow = row1 + row2  // pseudo-code but essentially add the two rows together
首先,这有意义吗

第二,这是一种自然的结合(对最终结果没有100%的信心)


第三,是更好的方法吗?

您可以使用astropy库来操作表。阅读两个表,然后使用
hstack
将两个行数相同的表连接在一起

from astropy.table import Table, hstack
from astropy.io import ascii
table1 = ascii.read("table1.dat")
table2 = ascii.read("table2.dat")  
print hstack([table1, table2], join_type='inner')
  • 是的,这是有道理的

  • 是的,如果索引[0]是唯一的公共列,则这是一个自然连接。但是,您应该像下面那样创建
    新行
    ,这样索引就不会在该行中重复:

    newRow = row1 + row2[1:]
    
  • 当前时间复杂度为O(n^2)。如果使用散列,则可以在O(n)时间复杂度中执行此操作,不过在本例中,散列的空间复杂度增加了O(n)

    hash = {}
    for idx, row1 in enumerate(table1):
        hash[row1[0]] = idx #save the index of row by the key value
    
    for row2 in table2:
        if hash.has_key(row2[0])
             newRow = table1[hash[row2[0]]] + row2[1:]
    

  • 遗憾的是,我不允许使用任何内部库,需要由我以编程方式完成。