首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python:创建unicode字符串的chararray

python:创建unicode字符串的chararray
EN

Stack Overflow用户
提问于 2020-11-05 08:41:45
回答 2查看 71关注 0票数 0

我需要在FITS文件中替换一些数据,我想用python3中的astropy.fits修改这些数据。为了与原始的FITS文件保持一致,我想写一个dtype='<U100'numpy.chararray

我尝试过使用numpy.chararray(x),其中x是一个字符串列表,我得到了*** TypeError: 'str' object cannot be interpreted as an integer

我很困惑,因为我认为在python 3中,所有的字符串都是unicode,而在我的理解中,'<U100'就是unicode。我想要一些关于我在这里做错了什么的提示

EN

回答 2

Stack Overflow用户

发布于 2020-11-05 19:35:46

FITS标准不处理unicode。在astropy.fits中,当您编写代码时,它将尝试编码为ASCII码。当您阅读FITS文件时,有一些魔法可以使ASCII bytes看起来像str

简而言之,如果您试图直接处理存储在FITS中的数据,则需要使用bytes。例如:

代码语言:javascript
复制
In [8]: s = np.array(['hello', 'world'])                                        

In [9]: np.char.encode(s, 'ascii')                                              
Out[9]: array([b'hello', b'world'], dtype='|S5')
票数 0
EN

Stack Overflow用户

发布于 2020-11-06 01:58:46

如果没有更多关于您要更改的内容的详细信息,很难说,但是假设您正在使用FITS表,最简单的方法可能是使用table API。

下面是一个示例表:

代码语言:javascript
复制
>>> from astropy.table import Table
>>> t = Table({'a': ['a', 'b', 'c']})
>>> t.write('table.fits')

您可以使用Table.read加载它,然后像任何字符串数组一样对其进行修改。它将正确地对其进行重新编码。

代码语言:javascript
复制
>>> 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 (这是内部实现细节):

代码语言:javascript
复制
>>> 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', 'e', 'f'], dtype='<U1')
>>> hdul[1].data['a'] = ['g', 'e', 'h']
>>> hdul[1].data['a']
chararray(['g', 'e', 'h'], dtype='<U1')
>>> hdul.writeto('table.fits', overwrite=True)
>>> hdul = fits.open('table.fits')
>>> hdul[1].data
FITS_rec([('g',), ('e',), ('h',)], dtype=(numpy.record, [('a', 'S1')]))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64689647

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档