合并两个astropy表

Merge two astropy tables

我有两个使用 astropy.table.Table 的 table,其中有一个唯一标识每一行的 ID 列。然而,这些行不一定都是相同的顺序。

Table 1:

 ID | A
----|---------
123 | 1.38e11
456 | 5.31e8
789 | 1.92e10

Table 2:

 ID | B
----|----
123 | 42
789 | 13
456 | 70

我想创建一个包含三列的 table:ID、A 和 B。

合并结果:

 ID | A       | B
----|---------|----
123 | 1.38e11 | 42
456 | 5.31e8  | 70
789 | 1.92e10 | 13

我可以在 table

中添加一列
table1['B'] = [42, 70, 13]

但是,值的顺序必须正确。

如何合并这些 table?


from astropy.table import Table

id = [123, 456, 789]
a = [1.38e11, 5.31e8, 1.92e10]
table1 = Table([id, a], names=('ID', 'A'), meta={'name': 'first table'})

id = [123, 789, 456]
b = [42, 70, 13]
table2 = Table([id, b], names=('ID', 'B'), meta={'name': 'second table'})

merged_table = ?

假设 ID 在两个 table 中相同(只是顺序不同),首先将两个 table 转换为 ndarrays,然后转置它们,以便table 中的列不会成为数组

中的行
import numpy as np

array1 = np.array([table1['ID'], table1['A']]).T
array2 = np.array([table2['ID'], table2['B']]).T

然后按第一列排序

sorted1 = array1[array1[:,0].argsort()]
sorted2 = array2[array2[:,0].argsort()]

合并两者

创建一个新的table
merged_table = Table([sorted1[:, 0], sorted1[:, 1], sorted2[:, 1]],
                     names=('ID', 'A', 'B'), meta={'name': 'merged table'})

Astropy 表支持一整套类似数据库的操作,包括合并、分组、堆叠等。谷歌搜索 "astropy table merge" 将带您到:

https://docs.astropy.org/en/stable/table/operations.html

因此,在您的情况下,只需执行以下操作:

 from astropy.table import join
 merged_table = join(table1, table2, keys='ID')