【问题标题】:Reading data file with unequal number of columns using numpy使用 numpy 读取列数不等的数据文件
【发布时间】:2019-03-17 02:11:45
【问题描述】:

我有一个带有数字的 .dat 文件。在第一行中,该文件有五列,在所有后续行中,它有四列。我希望能够使用 numpy 读取这个文件。目前尝试读取此文件时遇到以下错误:

In [3]: F1 = np.loadtxt(‘file.dat')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent 
call last)
<ipython-input-3-c0f31adaf29a> in <module>()
----> 1 F1 = np.loadtxt(‘file.dat')

/Users/usr/anaconda2/lib/python2.7/site-packages/numpy/lib/npyio.pyc in loadtxt(fname, dtype, comments, delimiter, converters, skiprows, usecols, unpack, ndmin, encoding)
   1090         # converting the data
   1091         X = None
-> 1092         for x in read_data(_loadtxt_chunksize):
   1093             if X is None:
   1094                 X = np.array(x, dtype)

/Users/usr/anaconda2/lib/python2.7/site-packages/numpy/lib/npyio.pyc in read_data(chunk_size)
   1014                 line_num = i + skiprows + 1
   1015                 raise ValueError("Wrong number of columns at line %d"
-> 1016                                  % line_num)
   1017 
   1018             # Convert each value according to its column and store

ValueError: Wrong number of columns at line 2 

如何使用 python 读取文件中除第一行之外的所有行? 我附上了一个示例文件here。

此外,此文件的第一列(减去第一行)有 n^2 行(在示例中,我有 n=3,列的条目是 1,2,3,4,5, 6,7,8,9)。我想读取第一列(减去第一行)并将其保存为形状为 (n,n) 的文本文件(即文本文件应该有 n 行和 n 列)。也就是说,我希望保存的矩阵具有以下顺序的条目:

1.0 2.0 3.0
4.0 5.0 6.0
7.0 8.0 9.0

如果能得到帮助,我将不胜感激。

【问题讨论】:

  • genfromtxt 在这方面稍微好一点,但它仍然需要正确数量的分隔符,这是默认white-space 的一个大问题。 usecols 可用于将负载限制为最小列数。你也可以告诉它跳过坏行。
  • 您可以逐行读取文件,将其拆分,并在行太短的情况下执行自己的更正。
  • hpaulj:你能举个例子吗?我是 python 新手,我无法实施您的建议。我会很感激的。

标签: python arrays python-2.7 numpy


【解决方案1】:

要做的一些实验:(未优化) 1. 读入文件行:

编辑:“file.dat”文件有空行。 if line.strip()... 子句是处理空行的。

with open('file.dat', 'r') as fhand:
    file_lines = [line[:-1] for line in fhand if line.strip() != ''] # remove the last character '\n'. **Remove empty lines**.

如果您不喜欢第一行,请将其删除。

file_lines.pop(0)

既然剩下的行的数字条目列数相同,您可以将每行的条目拆分,并进行类型转换:

mat_raw = [[float(term) for term in line.split()] for line in file_lines]

然后你会得到一个浮点矩阵。为了方便切片,将其转换为 numpy 数组。

mat = numpy.array(mat_raw)
# then you can do whatever you like. eg: first column
first_col = mat[:, 0]
# reshape it to n by n matrix:
res = first_col.reshape((n, n))
...

根据您的文件格式和您的目标,您可以优化此代码以供自己使用。

【讨论】:

  • 感谢郑的帮助。当我尝试您建议的技术时,我仍然会出现这个小错误:`first_col = mat[:, 0] IndexError: too many indices for array` 显然代码不喜欢行`first_col = mat[:, 0]` .我怎样才能解决这个问题?提前致谢。
  • @JiWonSong 嗨。当您输入mat = numpy.array(mat_raw) 时它会抱怨吗?如果这行执行了,你能告诉我这两行的结果吗? mat.shape 和 mat.dtype?
  • @JiWonSong 啊。我看到了问题。不知何故,file.dat 文件中有空行。在定义file_lines 时,添加一个if 子句即可。我已经更新了答案。
  • 非常感谢。编辑后,代码对我来说很好。
猜你喜欢
  • 2014-04-15
  • 2022-11-12
  • 2018-01-26
  • 2011-06-25
  • 1970-01-01
  • 2016-01-07
  • 1970-01-01
  • 2017-03-01
  • 2013-01-18
相关资源
最近更新 更多