Python Pandas:如何在读取文件时跳过列?

2024-04-27 07:46:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我的表格格式如下:

foo - bar - 10 2e-5 0.0 some information
quz - baz - 4 1e-2 1 some other description in here

当我和熊猫一起打开它时:

a = pd.read_table("file", header=None, sep=" ")

它告诉我:

CParserError: Error tokenizing data. C error: Expected 9 fields in line 2, saw 12

我基本上想要的是类似于skiprows选项的东西,它允许我做如下事情:

a = pd.read_table("file", header=None, sep=" ", skipcolumns=[8:])

我知道可以用awk重新格式化此表,但我想知道是否存在Pandas解决方案。

谢谢。


Tags: innonereadinformationfoo格式tablebar
2条回答

usecols参数允许您选择要使用的列:

a = pd.read_table("file", header=None, sep=" ", usecols=range(8))

但是,要接受不规则的列计数,还需要使用engine='python'

如果您使用的是Linux/OS X/Windows Cygwin,则应该能够按如下方式准备文件:

cat your_file |  cut -d' ' -f1,2,3,4,5,6,7 > out.file

然后在Python中:

a = pd.read_table("out.file", header=None, sep=" ")

示例:

输入:

foo - bar - 10 2e-5 0.0 some information
quz - baz - 4 1e-2 1 some other description in here

输出:

foo - bar - 10 2e-5 0.0
quz - baz - 4 1e-2 1

您可以在命令行上手动运行此命令,也可以使用^{} module从Python内部调用它。

相关问题 更多 >