python - 在 python pandas 中加载具有单独列的文本文件

标签 python pandas

我有一个如下所示的文本文件:

# Pearson correlation [n=344 #col=2]
# Name             Name              Value   BiasCorr   2.50%   97.50%  N: 2.50% N:97.50%
# ---------------  ---------------  -------- -------- -------- -------- -------- --------
  101_DGCA3.1D[0]  101_LEC.1D[0]    +0.85189 +0.85071 +0.81783 +0.87777 +0.82001 +0.87849

我已经使用以下代码将它加载到 python pandas 中:

import pandas as pd

data = pd.read_table('test.txt')
print data

但是,我似乎无法分别访问不同的列。我已经尝试使用 sep=' ' 并复制文本文件中各列之间的空格,但我仍然没有得到任何列名并尝试打印 data[0] 给我一个错误:

Traceback (most recent call last):
  File "cut_afni_output.py", line 3, in <module>
    print data[0]
  File "/home/user/anaconda2/lib/python2.7/site-packages/pandas/core/frame.py", line 1969, in __getitem__
    return self._getitem_column(key)
  File "/home/user/anaconda2/lib/python2.7/site-packages/pandas/core/frame.py", line 1976, in _getitem_column
    return self._get_item_cache(key)
  File "/home/user/anaconda2/lib/python2.7/site-packages/pandas/core/generic.py", line 1091, in _get_item_cache
    values = self._data.get(item)
  File "/home/user/anaconda2/lib/python2.7/site-packages/pandas/core/internals.py", line 3211, in get
    loc = self.items.get_loc(item)
  File "/home/user/anaconda2/lib/python2.7/site-packages/pandas/core/index.py", line 1759, in get_loc
    return self._engine.get_loc(key)
  File "pandas/index.pyx", line 137, in pandas.index.IndexEngine.get_loc (pandas/index.c:3979)
  File "pandas/index.pyx", line 157, in pandas.index.IndexEngine.get_loc (pandas/index.c:3843)
  File "pandas/hashtable.pyx", line 668, in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12265)
  File "pandas/hashtable.pyx", line 676, in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12216)
KeyError: 0

我无法手动设置标题行,因为 python 似乎将整个内容视为一列。如何将文本文件作为我可以调用的单独列读入?

最佳答案

试试这个:

In [33]: df = pd.read_csv(filename, comment='#', header=None, delim_whitespace=True)

In [34]: df
Out[34]:
                 0              1        2        3        4        5        6        7
0  101_DGCA3.1D[0]  101_LEC.1D[0]  0.85189  0.85071  0.81783  0.87777  0.82001  0.87849

关于python - 在 python pandas 中加载具有单独列的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45063786/

相关文章:

python - 最大化seaborn调色板中的色彩空间

python - 按具有多个值的列对 DF 进行排序

python - 如何在python中将字符串转换为数字

python - 下载 PDF 到子目录

python - Pandas :找到每个人最常见的字符串

python - 如何在数据框中减去?

csv - 将 pandas 列转换为逗号分隔列表以在 sql 语句中使用

python - 快速加载和处理9000万个元素的字典

Python - 值错误 : Cannot index with vector containing NA/NaN values

python - 使用 pandas 和 ipywidgets 创建交互式绘图,使用数据帧列中的值作为输入