[AstroPy] Changing table column from float64 to float32

Michael Brewer brewer at astro.umass.edu
Mon Jul 11 17:14:06 EDT 2022


Ivan,

Please try this:

table_hdu.replace_column('a', table_hdu.data['a'].astype(np.single))

Michael



On 7/11/22 12:17 PM, Peter Weilbacher wrote:
> Hi Ivan,
>
> I have no particular insight into this, but it seems to me that since
> you created the Column objects with a specific format, assigning any
> data to it will cause it to be casted to match that. (Otherwise the
> underlying memory buffer does not match.)
>
> Instead, I guess you could create a new column with the desired type and
> format and recreate the table using that:
>
> c1_single = fits.Column(name='a', array=table_hdu.data['a'].astype(np.single), format='E')
> table_hdu2 = fits.BinTableHDU.from_columns(c1_single + table_hdu.columns[1:])
>
> (It appears that you can even remove the .astype() from this and it
> still works.)
>
>     Peter.
>
> On Mon, 11 Jul 2022, Ivan Valtchanov wrote:
>
>> Hi all,
>> I have been trying to change a FITS BinTableHDU column from float64 to
>> float32. I tried three obvious paths to do so and they all failed. Here is
>> a very simple code to check.
>>
>> ####################
>> import numpy as np
>> from astropy.io import fits
>>
>> # create a simple table with float64 and float32
>> c1 = fits.Column(name='a', array=np.array([1,
>> 2],dtype=np.double),format='D')
>> c2 = fits.Column(name='b', array=np.array([3,
>> 4],dtype=np.single),format='E')
>> table_hdu = fits.BinTableHDU.from_columns([c1, c2])
>> #
>> # check columns types
>> for j in table_hdu.columns:
>>      print (j.name,j.dtype)
>> #a float64
>> #b float32
>> #=================
>> # first attempt to change float64 to float32
>> #
>> table_hdu.data['a'] = table_hdu.data['a'].astype(np.single)
>> #
>> for j in table_hdu.columns:
>>      print (j.name,j.dtype)
>> # Nope
>> #a float64
>> #b float32
>> #=================
>> # second attempt, also obvious
>> #table_hdu.data['a'].dtype = np.single
>> #
>> # Value error:  To change to a dtype of a different size, the array must be
>> C-contiguous
>> # not sure what this means...
>> #==================
>> # third attempt, list comprehension and creating a numpy array of type
>> float32
>> xx = np.array([float(v) for v in table_hdu.data['a']],dtype=np.single)
>> print (xx.dtype)
>> # float32
>> # Good, it's float32
>> table_hdu.data['a'] = xx
>> #
>> for j in table_hdu.columns:
>>      print (j.name,j.dtype)
>> # Nope, still a is float64
>> #a float64
>> #b float32
>> ############
>>
>> Is there something I'm missing?
>>
>> Using python 3.10, astropy 5.1, numpy 1.22.4
>>
>> Thanks,
>> Ivan
>>



More information about the AstroPy mailing list