Python 通过编程在两个表上进行自然连接
我有两个包含数据的表(实际上是列表列表列表),我希望通过编程方式在这两个表之间进行自然连接(没有SQL,只是在代码中) 如果我只想在索引[0]处的一个公共列上进行连接,我可以这样做: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
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')
新行
,这样索引就不会在该行中重复:
newRow = row1 + row2[1:]
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:]
遗憾的是,我不允许使用任何内部库,需要由我以编程方式完成。