read_table将所有数据读取到一列 [英] read_table read all data to one column
本文介绍了read_table将所有数据读取到一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的文件:
I got a file like this:
TCGA1 0 QWE
TCGA2 1 QWE
TCGA2 -2 RAF
TCGA3 2 KLS
并尝试使用熊猫将其读入数据框.
and tried to read it into a dataframe using pandas.
In [16]: df = pd.read_table('TR.txt',header=None)
但结果显示如下:
In [17]: df
Out[17]:
0
0 TCGA1 0 QWE
1 TCGA2 1 QWE
2 TCGA2 -2 RAF
3 TCGA3 2 KLS
列名已丢失,我该如何解决? 谢谢!
Column names has been missed, and how could I solve that? Thanks!
推荐答案
You have to add sep='s\+'
for separator arbitrary whitespace in read_table
.
它不能按预期工作,因为默认分隔符为,
,所以所有数据都在一列中.
It does not work as you expected, because default separator is ,
, so all data are in one column.
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
的解决方案:
Another solution with parameter 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
这篇关于read_table将所有数据读取到一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文