String read_table将所有数据读取到一列

String read_table将所有数据读取到一列,string,pandas,dataframe,String,Pandas,Dataframe,我有一个这样的文件: TCGA1 0 QWE TCGA2 1 QWE TCGA2 -2 RAF TCGA3 2 KLS In [17]: df Out[17]: 0 0 TCGA1 0 QWE 1 TCGA2 1 QWE 2 TCGA2 -2 RAF 3 TCGA3 2 KLS 并尝试使用pandas将其读入数据帧 In [16]: df = pd.read_table('TR.txt',header=None) 但结果是这样的: TCGA1 0 QWE

我有一个这样的文件:

TCGA1 0 QWE
TCGA2 1 QWE
TCGA2 -2 RAF
TCGA3 2 KLS
In [17]: df
Out[17]: 
          0
0   TCGA1 0 QWE
1   TCGA2 1 QWE
2  TCGA2 -2 RAF
3   TCGA3 2 KLS
并尝试使用pandas将其读入数据帧

In [16]: df = pd.read_table('TR.txt',header=None)
但结果是这样的:

TCGA1 0 QWE
TCGA2 1 QWE
TCGA2 -2 RAF
TCGA3 2 KLS
In [17]: df
Out[17]: 
          0
0   TCGA1 0 QWE
1   TCGA2 1 QWE
2  TCGA2 -2 RAF
3   TCGA3 2 KLS
缺少列名,我如何解决这个问题?
谢谢

您必须为分隔符中的任意空白添加
sep='s\+'

它不能像您预期的那样工作,因为默认分隔符是
,所以所有数据都在一列中

import pandas as pd
import io

temp=u"""TCGA1 0 QWE
TCGA2 1 QWE
TCGA2 -2 RAF
TCGA3 2 KLS"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_table(io.StringIO(temp), sep="\s+", header=None)
print df
       0  1    2
0  TCGA1  0  QWE
1  TCGA2  1  QWE
2  TCGA2 -2  RAF
3  TCGA3  2  KLS
另一个参数为delim_whitespace=True的解决方案:

import pandas as pd
import io

temp=u"""TCGA1 0 QWE
TCGA2 1 QWE
TCGA2 -2 RAF
TCGA3 2 KLS"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_table(io.StringIO(temp), delim_whitespace=True, header=None)
print df
       0  1    2
0  TCGA1  0  QWE
1  TCGA2  1  QWE
2  TCGA2 -2  RAF
3  TCGA3  2  KLS

谢谢你的帮助!我以前忽略了这一点。