【问题标题】:List to numpy array in scientific notation以科学计数法列出 numpy 数组
【发布时间】: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 解决方案也很受欢迎。

额外:我很感激任何可以摆脱标题行而无需创建/复制到任何新文件的解决方案。但这不是必需的。

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    显然,格式的重点是每个数字的字符长度始终相同,因此您可以利用它:

    matrix = []
    with open('test.txt') as data:
        for line in data.readlines()[3:]: 
            matrix.append([float(line[i : i + 20]) for i in (0, 20, 40, 60)]) 
        
    matrix = np.array(matrix)
    print(matrix)
    
    [[ 7.35334985e-03  0.00000000e+00  1.55096365e-25 -2.05314198e-27]
     [ 1.72329294e-25  1.34632261e-28  1.72329294e-25  1.34632261e-28]
     [ 4.48056165e-25  7.53940662e-26  6.72084248e-25  1.10936983e-25]
     [-6.46234854e-25 -1.19240161e-25 -5.60070206e-25 -5.69157884e-26]]
    

    【讨论】:

    • 这个很实用,谢谢!我还在习惯单行函数。
    猜你喜欢
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-02
    • 2018-11-19
    • 2011-10-18
    • 1970-01-01
    相关资源
    最近更新 更多