python - 设置 pandas.read_table 字段和记录分隔符

标签 python pandas

我正在尝试读取一个文件,该文件在一行中使用两个冒号 (::) 来分隔字段,并使用管道来分隔记录。因此,数据文件 test.txt 可能如下所示:

testcol1::testcol2|testdata1::testdata2

而我的代码如下:

pd.read_table('test.txt', sep='::', lineterminator='|')

这会产生以下警告:

C:\Users\jordan\AppData\Local\Enthought\Canopy\User\lib\site-packages\ipykernel\__main__.py:4: ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support regex separators; you can avoid this warning by specifying engine='python'.

以及以下“已解析”数据:

testcol1   testcol2|testdata1   testdata2

...具有三列、一个标题行和零个数据行。如果我添加 engine=c kwarg,我会得到以下错误:

ValueError: the 'c' engine does not support regex separators

似乎 Python 认为我的 :: 字段分隔符是正则表达式模式,因此迫使我使用不支持 lineterminator kwarg 的 Python 解析器.我如何告诉 pandas 使用 c 解析器,并为我的字段分隔符执行简单的字符串匹配而不是正则表达式匹配?

最佳答案

您可以使用速度更快的 c 引擎读取文件,因此您可以使用 lineterminator 参数,然后使用矢量化 str.split 拆分列和数据作为后处理步骤:

In [20]:
import pandas as pd
import io
t="""testcol1::testcol2|testdata1::testdata2"""
df = pd.read_csv(io.StringIO(t),  lineterminator=r'|')
df

Out[20]:
     testcol1::testcol2
0  testdata1::testdata2

In [37]:
df1 = df['testcol1::testcol2'].str.split('::', expand=True)
df1.columns = list(df.columns.str.split('::', expand=True)[0])
df1

Out[37]:
    testcol1   testcol2
0  testdata1  testdata2

关于python - 设置 pandas.read_table 字段和记录分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34755185/

相关文章:

python - 从 csv 文件中的 url 检索数据 - Python

python - 碎片 : UNFORMATTABLE OBJECT WRITTEN TO LOG

python - 在 pytest 中运行单个文件,该文件是 PEP 420 隐式命名空间包中的模块

python - 根据其他两列的相等性创建新列

python-2.7 - 在 groupby 数据框中应用唯一两次

python - Pandas 日期时间格式不起作用 - python

python - map 优化,按对象分组

python - to_dict() 在值周围创建括号

python - 无法解释的 Flask 404 错误

python - 根据字符串的首选顺序对可迭代对象进行排序