【问题标题】:Read txt file of this type in as a Python numpy.ndarray将这种类型的 txt 文件作为 Python numpy.ndarray 读取
【发布时间】:2018-03-25 12:22:00
【问题描述】:

我想在数据集 data.txt 上执行一些降维 (DR) 方法,例如 PCA、ICA 和 tSNE,也许 LEM 来比较这些方法。

因此,我需要将数据作为 numpy.ndarray 读取。 每行对应矩阵中的一行,分隔符 = ' '。

或者,我现在将文件作为一个 numpy.array 文件,但作为一个字符串:

[ '16.72083152\t12.91868366\t14.37818919\n' ... '16.9504402\t7.81951173\t12.81342726']

如何快速将其转换为所需格式的 numpy.array:n x 3,行分隔符 = ' ',每行元素之间的分隔符 = '\t' 将 '\n' 最后切掉?

非常感谢您的快速回答。其他提示也是如此。谢谢!

【问题讨论】:

  • 我建议你看看 Pandas 库,它有许多用于解析文本数据文件和数据分析的工具,还有 scikit-learn,它具有更复杂的降维和聚类技术。跨度>

标签: python arrays file numpy delimiter


【解决方案1】:

你可以试试下面的代码:

import numpy as np
data = np.loadtxt('data.txt',delimiter='\t') 

【讨论】:

    【解决方案2】:

    应该这样做

    import numpy 
    try: from StringIO import StringIO
    except ImportError: from io import StringIO
    
    foo = '16.72083152\t12.91868366\t14.37818919\n16.9504402\t7.81951173\t12.81342726\n'
    fn = StringIO.StringIO(foo) #make a file object from the string
    data = numpy.loadtxt(fn) #use loadtxt with default settings.
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多