我正在使用python实用程序从Tycho 2星级目录中获取数据。我正在处理的函数之一查询目录并返回给定星号(或星号标识符集)的所有信息。从字符串列表中创建一个numpy结构数组
我目前正在循环浏览目录文件的行,然后尝试将行解析为numpy结构数组(如果查询的话)。 (请注意,如果有更好的方法可以做到这一点,即使这个问题不是这个问题的关键,也可以让我知道 - 我这样做是因为目录太大而无法将其全部加载到内存中时间)
无论如何,一旦我确定了一个记录,我想保持我遇到了一个问题......我无法弄清楚如何解析它到一个结构化数组。
例如,假设我想保持的记录是:
record = '0002 00038 1| | 3.64121230| 1.08701186| 14.1| -23.0| 69| 82| 1.8| 1.9|1968.56|1957.30| 3|1.0|3.0|0.9|3.0|12.444|0.213|11.907|0.189|999| | | 3.64117944| 1.08706861|1.83|1.73| 81.0|104.7| | 0.0'
现在,我试图解析为numpy的结构阵列D型这样的:
dform = [('starid', [('TYC1', int), ('TYC2', int), ('TYC3', int)]),
('pflag', str),
('starBearing', [('rightAscension', float), ('declination', float)]),
('properMotion', [('rightAscension', float), ('declination', float)]),
('uncertainty', [('rightAscension', int), ('declination', int), ('pmRA', float), ('pmDc', float)]),
('meanEpoch', [('rightAscension', float), ('declination', float)]),
('numPos', int),
('fitGoodness', [('rightAscension', float), ('declination', float), ('pmRA', float), ('pmDc', float)]),
('magnitude', [('BT', [('mag', float), ('err', float)]), ('VT', [('mag', float), ('err', float)])]),
('starProximity', int),
('tycho1flag', str),
('hipparcosNumber', str),
('observedPos', [('rightAscension', float), ('declination', float)]),
('observedEpoch', [('rightAscension', float), ('declination', float)]),
('observedError', [('rightAscension', float), ('declination', float)]),
('solutionType', str),
('correlation', float)]
这似乎是它应该是一件相当简单的事情,但我所尝试的一切都是...
我试过了:
这两个给我
{TypeError}cannot perform accumulate with flexible type
这是没有意义的,因为它不应该做任何积累。
我也试过
np.array(re.split('\|| ',record),dtype=dform)
这抱怨
{TypeError}a bytes-like object is required, not 'str'
和另一种变体
np.array([x.encode() for x in re.split('\|| ',record)],dtype=dform)
不抛出一个错误,但也肯定不会返回正确的结果:
[ ((842018864, 0, 0), '', (0.0, 0.0), (0.0, 0.0), (0, 0, 0.0, 0.0), (0.0, 0.0), 0, (0.0, 0.0, 0.0, 0.0), ((0.0, 0.0), (0.0, 0.0)), 0, '', '', (0.0, 0.0), (0.0, 0.0), (0.0, 0.0), '', 0.0)...
那么我该如何做到这一点?我认为genfromtxt选项是要走的路(特别是因为偶尔会丢失数据),但我不明白为什么它不起作用。这是我只需要自己写一个解析器的东西吗?
嗯......你的'记录'有32个字段,但'dform'只有'17'。那个怎么样?我可以想象它可以通过'np.genfromtxt(BytesIO(record.encode()),dtype = dform,delimiter ='|')'来工作,但无论如何,现在它似乎是不明确的。 –
由于我没有足够的重新创建问题,请尝试将'str'切换到'np.str_' – TriHard8