【发布时间】:2021-11-02 08:22:12
【问题描述】:
我的数据文件由几行标题和 Nx4 大小的矩阵组成。我想从矩阵开始读取这个文件并将其保存到一个变量作为 numpy 数组。这些文件每个约为 300 MB,但示例文件如下所示:
# Some header line
Not all header lines start with a special character
# -- a keyword --
7.3533498487067E-03 0.0000000000000E+00 1.5509636485369E-25-2.0531419826552E-27
1.7232929428188E-25 1.3463226115772E-28 1.7232929428188E-25 1.3463226115772E-28
4.4805616513289E-25 7.5394066248323E-26 6.7208424769933E-25 1.1093698319396E-25
-6.4623485355705E-25-1.1924016124944E-25-5.6007020641611E-25-5.6915788404426E-26
如果值为正,则有一个空格,但如果值为负,则没有空格。 到目前为止,我尝试过:
matrix = []
with open('test.txt') as data:
for line in data.readlines()[3:]: # I always know how many header lines should be skipped.
matrix.append(line) # Saves all matrix elements into a list.
matrix = ' '.join([i for item in matrix for i in item.split()]) # Combines all matrix elements into a single string with correct single space separation.
matrix = np.fromstring(matrix, sep=' ') # This was supposed to convert the string into a 2D numpy array.
此代码产生错误:
'DeprecationWarning: string or file could not be read to its end due to unmatched data; this will raise a ValueError in the future.'
我认为它无法读取科学计数法(这可能是错误的),但我不知道如何修复它。另外,我认为通过将它从 list 转换为 str 到 numpy,我让它的时间比它应该的要长。如何使用 numpy 完成这项工作? Pandas 解决方案也很受欢迎。
额外:我很感激任何可以摆脱标题行而无需创建/复制到任何新文件的解决方案。但这不是必需的。
【问题讨论】: