Astropy Tables: set data type from another table

Viewed 163

I have one astropy.Table, call it 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

I want to create another table from a numpy array, but with the same columns and data types as T

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

I can create a table with the same column names

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

But if I try to pass the data types as well

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

then I get an error ValueError: dtype must be a list or None, and list(T.dtype) just returns TypeError: 'numpy.dtype' object is not iterable

How can I pass the data types from one table to another?

1 Answers

You can do this with the current release of astropy:

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

This is already improved in the master branch of astropy and in the next release version 4.2 of astropy you can do simply:

Table(A, dtype=T.dtype)
Related