我想从 astropy 表中删除包含 infs 的行。类似于以下内容
for line in mytable:
if float('inf') in line:
mytable.remove(line)
除了我不知道remove
函数使用什么。
在文档中,它说明了如何删除列,但没有说明如何删除行。
这比您的答案快一点,特别是随着表格的大小增长。
在这里,我们inf
通过将每列掩码组合在一起来制作包含所有行的掩码,而不是将整个表切片一次:
>>> 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
我们在这两种情况下所做的并不是真正“删除行”本身,因为我们没有修改原始表。相反,我们正在创建一个新表作为原始表的副本,其中省略了一些行。因此,按照您的方式进行操作会比较慢,因为对于每一列,它都必须制作表的新副本,而无论有多少列,首先创建掩码然后索引只会制作一次副本:
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)
我怀疑对于更多的列和/或行,差异甚至更大。
根据您的用例是什么,您还可以考虑创建一个带有每列掩码的掩码表。这允许您避免从表中删除数据,同时仍然对其执行忽略奇异值的算术运算:
>>> 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句