python - NumPy genfromtxt 对于不同的列大小

标签 python numpy genfromtxt

我正在尝试使用 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 灵活调整列大小?

最佳答案

文本文件的格式似乎不适合分析。我建议使用 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 找到。

关于python - NumPy genfromtxt 对于不同的列大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34180333/

相关文章:

python - -9999 作为 numpy.genfromtxt() 的缺失值

string - python : Convert string (in scientific notation) to float

python - 添加随机字节如何*增加*重复项?

python - python字典中没有值

python - getopts Values 类和 Template.Substitute 不(立即)一起工作

Python Numpy 安装健全性检查错误

python - 在python中将图像转换为矩阵

python - Matplotlib,控制 mark_inset() 属性(kwargs)

python - 组合嵌套列表并查找顺序

python - 从文本文件中将数据读入 numpy 数组