问题描述
我需要用python3中的FITS
替换astropy.fits
文件中的一些数据。为了与原始FITS文件保持一致,我想写一个numpy.chararray
的{{1}}。
我尝试使用dtype='<U100'
,其中numpy.chararray(x)
是字符串列表,但我得到了x
。
我很困惑,因为尽管在*** TypeError: 'str' object cannot be interpreted as an integer
中所有字符串都是unicode,而据我所知python 3
是unicode。我很想知道我在这里做错了什么
解决方法
FITS标准不处理unicode。在编写astropy.fits时,它将尝试编码为ASCII。当您读取FITS文件时,引擎盖下会出现一些魔术,使ASCII myUniqueList = []
def add(n):
myUniqueList.append(n)
print(myUniqueList)
add(5)
看起来像bytes
。
简短的答案是,如果您试图直接处理FITS中存储的数据,则需要使用str
。例如:
bytes
,
没有确切的详细信息要更改,很难说,但是假设您正在使用FITS表,最简单的方法可能就是使用Table API。
这是一个示例表:
>>> from astropy.table import Table
>>> t = Table({'a': ['a','b','c']})
>>> t.write('table.fits')
您可以使用Table.read
加载它,并像修改任何字符串数组一样对其进行修改。它将正确处理重新编码。
>>> t = Table.read('table.fits')
>>> t
<Table length=3>
a
bytes1
------
a
b
c
>>> t['a'] = ['d','e','f']
>>> t.write('table.fits',overwrite=True)
>>> t = Table.read('table.fits')
>>> t
<Table length=3>
a
bytes1
------
d
e
f
如果您想直接使用较低级别的FITS界面,也可以。在大多数情况下,不必手动构建chararray
(这是内部实现的详细信息):
>>> from astropy.io import fits
>>> hdul = fits.open('table.fits')
>>> hdul[1].data
FITS_rec([('d',),('e',('f',)],dtype=(numpy.record,[('a','S1')]))
>>> hdul[1].data['a']
chararray(['d','f'],dtype='<U1')
>>> hdul[1].data['a'] = ['g','h']
>>> hdul[1].data['a']
chararray(['g','h'],dtype='<U1')
>>> hdul.writeto('table.fits',overwrite=True)
>>> hdul = fits.open('table.fits')
>>> hdul[1].data
FITS_rec([('g',('h','S1')]))