【问题标题】:Turn .txt file into matrix of ints in python将.txt文件转换为python中的整数矩阵
【发布时间】:2018-02-17 04:12:25
【问题描述】:

如果我有一个 txt 文件,其内容如下:

4 2 45 21
0 92 12 2
345 9 3 4
1 2 39 93

有没有一种快速简便的方法可以将其转换为 int 矩阵?

现在,我已经通过这种方式访问​​了该文件:

file = open(testFile, 'r')
data = []
for row in file:
    data.append(row)

这会将数据存储为一个数组,其中每一行都是一个字符串。与其通过转换数据类型然后将其转换为矩阵,有没有一种方法可以在我读入时立即以矩阵形式将这些数据存储为整数?

【问题讨论】:

标签: python python-2.7 matrix file-io


【解决方案1】:

这样做的简单方法是:

>>> for row in file:
...     data.append([int(x) for x in row.split()])
...
>>> data
[[4, 2, 45, 21], [0, 92, 12, 2], [345, 9, 3, 4], [1, 2, 39, 93]]

IMO,这是最pythonic的方式

【讨论】:

    【解决方案2】:

    对于嵌套列表:

    text = """4 2 45 21
    0 92 12 2
    345 9 3 4
    1 2 39 93"""
    
    [[*map(int, line.split())] for line in text.split('\n')]
    
    Out[16]: [[4, 2, 45, 21], [0, 92, 12, 2], [345, 9, 3, 4], [1, 2, 39, 93]]
    

    【讨论】:

      【解决方案3】:

      如果您可以将数据存储为numpy.ndarray,您可以使用numpy 的genfromtext() 并将dtype 标志设置为int

      from StringIO import StringIO
      import numpy as np
      
      text = """4 2 45 21
      0 92 12 2
      345 9 3 4
      1 2 39 93"""
      
      a = np.genfromtxt(StringIO(text), dtype=int)  #replace the arg with your filename
      
      print(a)
      #[[  4   2  45  21]
      # [  0  92  12   2]
      # [345   9   3   4]
      # [  1   2  39  93]]
      

      另一种方法是使用loadtxt() 而不是genfromtxt(),正如@Zhiyacomments 中指出的那样。

      a = np.loadtxt(StringIO(text), dtype=int)
      

      根据this post,除了genfromtxt()提供了更多处理缺失数据的选项之外,这两个功能基本相同。

      【讨论】:

        猜你喜欢
        • 2017-11-03
        • 1970-01-01
        • 2020-10-17
        • 2021-12-29
        • 1970-01-01
        • 2021-11-25
        • 2015-07-26
        • 1970-01-01
        • 2017-05-07
        相关资源
        最近更新 更多