程序matically对两个表进行自然连接
我有两个表(实际上是列表的列表),里面包含一些数据,我想在代码中自然地把这两个表连接起来(不使用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
首先,这样做合理吗?
其次,这算是自然连接吗(我对最后的结果不是很有信心)?
第三,有没有更好的方法来实现这个?
2 个回答
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
是的,这样做是有道理的。
是的,如果index[0]是唯一的公共列,那么这就是一个自然连接。不过,你应该像下面这样创建
newRow
,这样行内的索引就不会重复: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:]