首页 > 解决方案 > Astropy Tables:从另一个表中设置数据类型

问题描述

我有一个astropy.Table,叫它T

  a      b     c      d
int32 float64 str1 float64
----- ------- ---- -------
    1     2.0    0    10.0
    4     5.0    1    20.0
    5     8.5    2    30.0

我想从一个 numpy 数组创建另一个表,但具有相同的列和数据类型T

import numpy as np
A = np.array([
  [1, 2, 3, 4],
  [5, 6, 7, 8]])

我可以创建一个具有相同列名的表

S = Table(A, names=T.colnames)

但是如果我也尝试传递数据类型

S = Table(A, names=T.colnames, dtype=T.dtype)

然后我得到一个错误ValueError: dtype must be a list or None,然后list(T.dtype)返回TypeError: 'numpy.dtype' object is not iterable

如何将数据类型从一个表传递到另一个表?

标签: python-3.xnumpyastropy

解决方案


您可以使用当前版本的 astropy 执行此操作:

Table(A, names=T.colnames, dtype=[T[name].dtype for name in T.colnames])

这已经在 astropy 的 master 分支中得到了改进,在 astropy 的下一个版本 4.2 中,您可以简单地执行以下操作:

Table(A, dtype=T.dtype)

推荐阅读