【问题标题】:Python read arrays delimited by white space from columns in a filePython从文件中的列中读取由空格分隔的数组
【发布时间】:2017-11-23 16:43:21
【问题描述】:

我有一个结构如下的文件:

1
2
3

23
33
55

1
2
4

...

等等。所以我想将数据提取到一个多维数组中,即[[1,2,3], [23,33,55], [1,2,4]...]。到目前为止,我已经尝试使用numpy.loadtxt() 函数,但是我得到了一个包含所有数字的一维数组,并且还尝试了这个 sn-p:

data_tot = []
with open('file.txt', 'r') as infile:
     for line in infile:
         if line.rstrip() != '':
            data = []
            data.append(line.rstrip())
         else:
            data_tot.append(data)

data_tot 是我想要的数组,但我得到类似data_tot = [[1], [23], [1] ...]

关于如何解决这个问题的任何想法。提前致谢。

【问题讨论】:

  • 您介意使用 pandas 还是需要使用 open: ???
  • 不,可以用pandas。
  • 好的,元素的数量是固定的吗?例如3 然后 3 然后 3 等等 ??
  • 是的,已修复

标签: python arrays file


【解决方案1】:

您可以使用 reshape 更改 numpy 数组的形状

#reshape the array to 3 by n 
np.loadtxt("file.txt").reshape(-1,3)

你的数据应该提供哪些:

[[  1.   2.   3.]
 [ 23.  33.  55.]
 [  1.   2.   4.]
 ...]

【讨论】:

  • 我猜你的意思是np.loadtxt("file.txt").reshape(-1,3)
  • 很好的解决方案,因为元素的数量是固定的
【解决方案2】:

在你提供的sn-p中,每次不为空时,data列表被清空。

data_buf = []
data_tot = []
with open('file.txt', 'r') as infile:
     for line in infile:
         if line.rstrip() == '':
            data_tot.append(data_buf[:])
            data_buf = []
         else:
            data_buf.append(line.rstrip())
if len(data_buf) > 0:
    data_tot.append(data_buf[:])

注意 data_buf[:] 复制列表对象以避免在下一次迭代中对其进行修改。如果最后一个缓冲区后面没有空行,您还应该将最后一个缓冲区添加到总列表中。

这是使用 StringIO 而不是文件的完整独立示例代码

import io

f = io.StringIO("""1
2
3

23
33
55

1
2
4
""")
data_buf = []
data_tot = []
with f as infile:
     for line in infile:
         if line.rstrip() == '':
            data_tot.append(data_buf[:])
            data_buf = []
         else:
            data_buf.append(line.rstrip())
data_tot.append(data_buf[:])

【讨论】:

    猜你喜欢
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多