Python Astropy: 字符串转整数

0 投票
1 回答
929 浏览
提问于 2025-04-18 02:03

我有一个叫input_table的astropy表格,其中有一个字段/列叫'observation_id',里面包含像81-126这样的对象。我想把这两个数字(81和126)分开,并把它们保存为整数。我在这里写下所有步骤,以展示每一步我所处理的对象类型。如果有什么不清楚的地方,请告诉我。

In [62]: id=input_table['observation_id']

In [63]: str=id[0]

In [64]: print(str)
81-126

In [65]: print(type(str))
<class 'numpy.str_'>

In [66]: nx,ny=str.split("-")

In [67]: print(nx,ny)
81 126

In [68]: print(type(nx),type(ny))
<class 'str'> <class 'str'>

当我尝试下面的方法把字符串转换成整数时,

In [70]: int(float(nx))

我得到了:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-70-7cfc33470a5c> in <module>()
----> 1 int(float(nx))

ValueError: could not convert string to float: '8\x00\x00\x001\x00\x00\x00'

查看这个链接,了解字符串'8\x00\x00\x001\x00\x00\x00'的类型

我尝试了

In [71]: nx,ny=str.decode(encode='utf-16-le').split('-')

但我得到了

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-71-5f8d49af6ed1> in <module>()
----> 1 nx,ny=str.decode(encode='utf-16-le').split('-')

AttributeError: 'numpy.str_' object has no attribute 'decode'

我不知道接下来该怎么做。有人能帮忙吗?

1 个回答

0

我在Python 2.7或3.3版本中,使用numpy 1.7无法重现你的例子。你能提供更多关于版本和平台的具体信息吗?

有一点需要注意的是,你把str当作变量名,这样会覆盖掉内置的str类型。我觉得这在这里不一定是个问题,但一般来说,这样做并不是个好主意。

撰写回答