【发布时间】:2020-10-31 13:27:41
【问题描述】:
通常我用 SQL 查询一个在线数据库,但数据库已关闭。我有一个 H5 文件,其中包含我需要查询的表。我使用Table.read_where('condition') 查询了该表,并且对于符合我的标准的每一行都有一个numpy.void 元素列表。有什么方法可以将该行列表放入 Astropy 表中?这就是我以前使用的所有代码,我宁愿不必更改它。这是我一直用来尝试将其转换为 Astropy 表的代码:
import tables
from astropy.table import Table
import numpy as np
Data = tables.open_file('file_path','r') #opens our .h5 file
DataTable = Data.root.TableName #Points to the table
#Queries the table for rows that meet my 'Condition', and outputs a list of numpy.void's
#containing integers and floats. Each numpy.void represents a row in my table.
result = [row for row in DataTable.read_where('Condition')]
#I try to turn the list of rows into a Astropy table to use in the rest of my code.
resultTable = Table(rows=result,names=('Column1','Column2','Column3'))
我得到的错误是:
Traceback (most recent call last):
File "<ipython-input-2-aa9501cdbf2a>", line 1, in <module>
runfile('FilePath', wdir='FilePath')
File "Spyder File", line 827, in runfile
execfile(filename, namespace)
File "Spyder File", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "File Path", line 27, in <module>
resultTable = Table(rows=result,names=('Column1','Column2','Column3'))
File "FilePath/python3.7/site-packages/astropy/table/table.py", line 420, in __init__
rec_data = recarray_fromrecords(rows)
File "FilePath/lib/python3.7/site-packages/astropy/table/np_utils.py", line 196, in recarray_fromrecords
return np.rec.fromarrays(array_list, formats=formats)
File "FilePath/lib/python3.7/site-packages/numpy/core/records.py", line 645, in fromarrays
_array[_names[i]] = arrayList[i]
ValueError: Can't cast from structure to non-structure, except if the structure only has a single field.
我尝试通过np.rec.fromrecords 传递result 以检查这是否有效,因为[Astropy 文档] (https://docs.astropy.org/en/stable/table/construct_table.html#construct-table) 说它必须能够通过该函数。它可以正常工作,没有任何错误。我不知道从这里去哪里。
我的替代计划是创建一个由result 中的行组成的 PyTables 表,并从中提取列作为 numpy 数组。我宁愿坚持只使用 Astropy,因为我使用的代码是围绕 Astropy 构建的,坚持使用它会更容易,而不是通过将其更改为 PyTables。
【问题讨论】:
-
首先,没有 scipy 表之类的东西。你导入了我几乎没有经验的两件事,
astropy.table和tables(是Pytables?)它看起来有点像一个或两个使用numpy结构化数组(又名recarray)。您指的是什么scipy文档?此外,当询问错误时,显示整个错误,包括回溯。 -
PyTables(表)函数
DataTable.read_where('Condition')返回一个匹配表描述的 NumPy 记录数组。这就是您在创建 astropy.table 时想要的(如果我了解 astropy 文档。不确定它是否可以使用记录数组)。你不需要row for row in——只需使用result = DataTable.read_where('Condition')。 astropy.table 可能需要您将记录数组转换为 ndarray。我会让你弄清楚。 -
结构化数组(和 recarray)记录在 numpy.org/doc/1.19/user/basics.rec.html 中。
numpy.lib.recfunctions子模块现在有一个structured_to_unstructured函数,可以很好地将结构化数组转换为传统的多维数组。 -
谢谢大家的建议。我错误地混淆了 AstroPy 和 SciPy。这是我的意思的文档:docs.astropy.org/en/stable/table/… 我需要做的就是用实际的 read_where 命令切换迭代的
row for row in。谢谢!我是 Pytables 的新手,一直在复制他们的基本示例。 -
这是否意味着您的问题已解决? “我需要做的就是用实际的 read_where 命令切换迭代
row for row in。”
标签: python numpy pytables astropy