【问题标题】:Read float and string from txt从 txt 读取浮点数和字符串
【发布时间】:2014-02-03 22:02:26
【问题描述】:

我有一个包含字符串和浮点数的 txt(见下文),我需要将数据加载到矩阵中。最好的方法是什么?

虚拟数据行:

1 2 3.0 4.567 8.910 Data/file.txt

以下是我的(非工作)代码。它不返回前三个变量,也不换行。

import numpy as np
import scipy

matrix = []
with open('input.txt') as f:
    for line in f:
    el = line.split()
    matrix.append(el[0] + el[1] + el[2] + el[3] + el[4] + el[5])
print matrix

【问题讨论】:

  • ...您通常不希望在 numpy 矩阵中混合数据类型
  • 我知道,但我需要和这头野兽一起工作
  • 所有行的格式都一样?
  • 我看不出你想得到什么结果。

标签: python file numpy io


【解决方案1】:

每行的条目数是否相同?如果是这样,我建议使用pandas。使用read_csv函数并指定分隔符为\s+

如果您希望它是表格的,请将其存储在数据框中。

【讨论】:

    【解决方案2】:

    它对我有用。 for循环的缩进是不是错字?

    import numpy as np
    import scipy
    
    matrix = []
    with open('input.txt') as f:
        for line in f:
            el = line.split()
            matrix.append(el[0] + el[1] + el[2] + el[3] + el[4] + el[5])
    print matrix
    

    输出:['123.04.5678.910Data/file.txt']

    【讨论】:

      【解决方案3】:

      您可以将numpy.genfromtxtdtype=None 一起使用:

      >>> import numpy as np
      >>> np.genfromtxt('input.txt', dtype=None)
      array((1, 2, 3.0, 4.567, 8.91, 'Data/file.txt'), 
            dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<f8'), ('f3', '<f8'), ('f4', '<f8'), ('f5', 'S13')])
      

      【讨论】:

        猜你喜欢
        • 2017-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-15
        • 1970-01-01
        • 1970-01-01
        • 2020-08-04
        • 1970-01-01
        相关资源
        最近更新 更多