将行从 astropy table 转换为 numpy 数组

Converting a row from an astropy table to a numpy array

我有一个 numpy table

<Table length=3>
  a     b  
int64 int64
----- -----
    1     3
    2     5
    4     7

我想将一行转换为一个 numpy 数组。但是当我尝试时,我最终得到一个没有维度的数组

In: np.array(mytable[0]).shape
Out: ()

如果我这样做

myrow = mytable[0]
myrow[0]

我收到错误

IndexError: too many indices for array

有没有类似 t[0].values 我可以做的事情 return array([1, 3]) ?

当你从 Astropy 中的 table 中切出一行并转换为 ndarray 时,你会得到一个 0D 结构化数组,即 shape 属性为空。对于通用解决方案,numpy 提供了一种 structured_to_unstructured 方法,该方法不仅适用于单个行切片。


>>> np.lib.recfunctions.structured_to_unstructured(np.array(t[0]))
array([1, 3])

>>> np.lib.recfunctions.structured_to_unstructured(np.array(t[1:]))
array([[2, 5],
       [4, 7]])

Table.Row 对象提供了对值的迭代器,因此您可以:

>>> np.array(list(t[0]))
array([1, 3])