从 astropy table 中删除行

Remove row from astropy table

我想从 astropy table 中删除包含 infs 的行。类似下面的内容

for line in mytable:
    if float('inf') in line:
        mytable.remove(line)

只是我不知道 remove 函数要用什么。

the documentation中,它说明了如何删除列,但没有说明如何删除行。

执行以下操作似乎有效

for col in mytable.colnames:
    mytable = mytable[mytable[col] != float('inf')]

这比 稍微快一点,尤其是随着 table 的大小增长。

在这里,我们通过将每列掩码或运算在一起来制作包含 inf 的所有行的掩码,而不是将完整的 table 切片一次:

>>> table = Table({'a': [1, 2, 3], 'b': [1.0, np.inf, 3.0], 'c': [np.inf, 2.0, 3.0]})
>>> mask = np.logical_or.reduce([c == np.inf for c in table.columns.values()])
>>> table = table[~mask]
>>> table
<Table length=1>
  a      b       c
int64 float64 float64
----- ------- -------
    3     3.0     3.0

我们在这两种情况下所做的并不是真正的 "removing rows" 本身,因为我们没有修改原始 table。相反,我们正在创建一个新的 table 作为原始 table 的副本,其中省略了一些行。因此,按照您的方式进行操作会比较慢,因为对于每一列,它都必须制作 table 的新副本,而无论有多少列,首先创建掩码然后索引只制作一次副本:

In [24]: %%timeit
    ...: table2 = table
    ...: for col in table.colnames:
    ...:     table2 = table2[table2[col] != float('inf')]
    ...:
327 µs ± 40.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [25]: %%timeit
    ...: mask = np.logical_or.reduce([c == np.inf for c in table.columns.values()])
    ...: table2 = table[~mask]
    ...:
    ...:
121 µs ± 7.84 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

我怀疑对于更多的列 and/or 行,差异会更加显着。

根据您的用例,您还可以考虑创建一个带有每列掩码的 masked table。这使您可以避免从 table 中删除数据,同时仍然对其执行忽略奇异值的算术运算:

>>> table = Table({'a': [1, 2, 3], 'b': [1.0, np.inf, 3.0], 'c': [np.inf, 2.0, 3.0]}, masked=True)
>>> for col in table.columns.values():
...     col.mask = (col == np.inf)
...
>>> table
<Table masked=True length=3>
  a      b       c
int64 float64 float64
----- ------- -------
    1     1.0      --
    2      --     2.0
    3     3.0     3.0
>>> table['b'].mean()
2.0