python - 使用 Python 导入包含文本和数字数据的文件

标签 python python-2.7 pandas numpy

我有一个 .txt 文件,其中包含文本数据和数字数据。文件的前两行以文本数据形式包含基本信息,而第一列(我将第零列称为第一列)也以文本形式包含基本数据。在文件中的所有其他位置,数据都是数字形式。我希望使用 python 中的库分析文件中存在的数值数据,最好是 numpy 或 pandas,或两者的组合(回归、相关、scikit-learn 等分析)。我重申,文件中的所有数据对于我的分析都是必要的。以下快照(取自 Excel)显示了我的数据所在格式的截断版本:enter image description here

此快照中显示的数据可以找到here.

特别是,我想要的是能够使用 python(numpy 或 pandas)从该文件中导入所有数值数据,并能够使用前两行中的文本数据引用该数据中的特定行(类型、标记)和第一列(对象编号)。在我的实际数据文件中,我有数十万行(对象类型)和数十列。

我已经尝试使用 numpy.loadtxt(...)pandas.read_csv(...) 打开这个文件,但我遇到了错误,或以笨拙的格式加载数据。我真的很感激能就如何以某种方式在 python 中导入文件提供一些指导,以便我拥有我想要的功能。

最佳答案

如果我是你,我会使用 pandas,并使用如下方式导入它:

df = pd.read_csv('dum.txt',sep='\t', header=[0,1], index_col=0)

这为您提供了数据框:

>>> df
Type      T1   T2   T3   T4   T5
Tag     Good Good Good Good Good
object1  1.1  2.1  3.1  4.1  5.1
object2  1.2  2.2  3.2  4.2  5.2
object3  1.3  2.3  3.3  4.3  5.3
object4  1.4  2.4  3.4  4.4  5.4
object5  1.5  2.5  3.5  4.5  5.5
object6  1.6  2.6  3.6  4.6  5.6
object7  1.7  2.7  3.7  4.7  5.7
object8  1.8  2.8  3.8  4.8  5.8

并且您所有的列都是 float :

>>> df.dtypes
Type  Tag 
T1    Good    float64
T2    Good    float64
T3    Good    float64
T4    Good    float64
T5    Good    float64
dtype: object

它包含一个多索引列标题:

>>> df.columns
MultiIndex(levels=[['T1', 'T2', 'T3', 'T4', 'T5'], ['Good']],
           labels=[[0, 1, 2, 3, 4], [0, 0, 0, 0, 0]],
           names=['Type', 'Tag'])

还有一个包含来自 Type 的信息的常规索引:

>>> df.index
Index(['object1', 'object2', 'object3', 'object4', 'object5', 'object6',
       'object7', 'object8'],
      dtype='object')

此外,您可以将您的值转换为numpy floats 数组,只需使用:

>>> df.values
array([[1.1, 2.1, 3.1, 4.1, 5.1],
       [1.2, 2.2, 3.2, 4.2, 5.2],
       [1.3, 2.3, 3.3, 4.3, 5.3],
       [1.4, 2.4, 3.4, 4.4, 5.4],
       [1.5, 2.5, 3.5, 4.5, 5.5],
       [1.6, 2.6, 3.6, 4.6, 5.6],
       [1.7, 2.7, 3.7, 4.7, 5.7],
       [1.8, 2.8, 3.8, 4.8, 5.8]])

关于python - 使用 Python 导入包含文本和数字数据的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52508642/

相关文章:

python - 导入 scikit-learn 模块时出错

python - 如何在 matplotlib 中删除环形图的偏离中心部分?

python - 使用以数字数组命名的列迭代 DataFrame

Django反向查询集包含列表中的所有值

python - Pandas 多索引数据框中各组之间的计算

python - 数据透视表中附加的行/列/总计的总和

python - 在同一行上创建 for 语句,但不在下一个输入上创建 for 语句

python - 将 DataFrame 中的值替换为 None

Python numpy 解包函数

python - 更改 Pandas DataFrame 数据点的值