【问题标题】:NumPy genfromtxt for different column sizes用于不同列大小的 NumPy genfromtxt
【发布时间】:2015-12-09 13:44:30
【问题描述】:

我正在尝试使用 numpy.genfromtxt() 方法从 txt 文件中提取值。我的 txt 文件如下所示:

 '! dt         tot            nsave     readext\n',
 '  0.002      200            500       F\n',
 '!----------------------------------------------------------------------\n',
 '! xdomain       ydomain \n',
 '  7.5           7.5\n',
 '!----------------------------------------------------------------------\n',
 '! maxnewts  maxiters  atol\n',
 '  40        100       0.001\n',
 '!----------------------------------------------------------------------\n',
 '! p      \n',
 '  600  \n',

但是使用numpy.genfromtxt("file.txt", comments='!') 给了我:

Line #4 (got 2 columns instead of 4)
Line #7 (got 3 columns instead of 4)
Line #10 (got 1 columns instead of 4)

如何让numpy.genfromtxt 灵活调整列大小?

【问题讨论】:

    标签: python numpy genfromtxt


    【解决方案1】:

    似乎文本文件的格式不适合分析。我建议使用csv 从文件中获取您需要的内容,然后使用numpy 进行处理

    import csv
    clean_vars = []
    with open('foo.txt', 'r') as csvfile:
        reader = csv.reader(csvfile, delimiter=' ', quotechar=",")
        for row in reader:
            # clean up your file here and append it to the list
            clean_vars.append([char for char in row if char])
    
    # do your processing with numpy with your clean vars
    

    在上述情况下,我以低效清理变量为例。 csv 的文档可以在 https://docs.python.org/2/library/csv.html

    找到

    【讨论】:

      猜你喜欢
      • 2012-05-10
      • 2017-03-21
      • 1970-01-01
      • 2015-11-22
      • 1970-01-01
      • 2013-01-14
      • 2021-03-06
      • 1970-01-01
      • 2020-11-26
      相关资源
      最近更新 更多