在两条特定行之间使用 np.loadtxt (Python 2.7)

Using np.loadtxt between two specific lines (Python 2.7)

我知道 np.loadtxt 允许您从文本文件的列中快速提取数据,而且我知道您可以使用 skiprows 跳过前 N 行。您能否指定 end 行号,以便 np.loadtxt 仅提取文本文件中两个已知行号之间的文本?

在下面的例子中,您可以指定:

(dat1,dat2) = np.loadtxt(file, skiprows = 1, usecols = (0,1), unpack=True)

但是我收到一条错误消息说 "ValueError: could not convert string to float: Data1"

示例: 1 Data1 Data2 Data3 2 1 3 5 3 7 1 6 [...] 48 8 9 2 49 2 7 6 50 Data1 Data2 Data3 51 5 6 1 52 9 12 3 53 1 0 2

np.genfromtxt

skip_header : int, optional
    The number of lines to skip at the beginning of the file.
skip_footer : int, optional
    The number of lines to skip at the end of the file.
max_rows : int,  optional
    The maximum number of rows to read. Must not be used with skip_footer
    at the same time.  If given, the value must be at least 1. Default is
    to read the entire file.

对读取的行进行大量控制。

另一种选择是自己打开文件,例如

with open('myfile', 'rb') as f:
     <skip>
     np.genfromtxt(f, ...)
     etc

并将其传递给 genfromtxt。你甚至可以一行一行地喂它。 genfromtxt(和 loadtxt)对任何为其提供行的东西感到满意 - 文件、行列表、行生成器等。