【问题标题】:Using np.loadtxt between two specific lines (Python 2.7)在两个特定行之间使用 np.loadtxt (Python 2.7)
【发布时间】:2017-02-27 15:37:04
【问题描述】:

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

在以下示例中,您可以指定:

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

但我收到一条错误消息,提示“ValueError:无法将字符串转换为浮点数: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

【问题讨论】:

  • genfromtxt 有一个最大行数参数
  • 这正是我一直在寻找的,尤其是考虑到genfromtxt 描述:“numpy.loadtxt - 没有数据丢失时的等效函数。”如果您将您的回复作为解决方案,我将接受它作为解决方案。

标签: python python-2.7 numpy data-extraction


【解决方案1】:

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)对任何提供行的东西都很满意——文件、行列表、行生成器等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-28
    • 1970-01-01
    • 2021-12-19
    相关资源
    最近更新 更多