以编程方式在两个表上进行自然连接

时间:2014-08-23 13:14:23

标签: python

我有两个包含数据的表(实际列表列表),我想以编程方式在两者之间进行自然连接(没有SQL - 仅在代码中)。

如果我只想加入Index [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%的信心)

第三 - 是更好的方法吗?

2 个答案:

答案 0 :(得分:1)

您可以使用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')

答案 1 :(得分:1)

  1. 是的,这很有意义

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

    newRow = row1 + row2[1:]
    
  3. 当前时间复杂度为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:]
    
相关问题