首页 > 解决方案 > 带正则表达式的 read_csv

问题描述

csv 数据示例:

<pre>2019-08-15 00:00:06,430 0:0 - {"info":{"name":"LTD - PUBLIC"}}</pre>
<pre>pd.read_csv(filepath, sep= ' - ', header=None, engine='python')</pre>

预期的:

<pre>
date                           info
2019-08-15 00:00:06,430 0:0    {"info":{"name":"LTD - PUBLIC"}}
</pre>

错误信息:

ParserError: Expected 2 fields in line 1, saw 3. 错误可能是由于使用多字符分隔符时忽略引号引起的。

标签: pythonpandas

解决方案


使用regexsep

temp = StringIO("""  
2019-08-15 00:00:06,430 0:0 - {"info":{"name":"LTD - PUBLIC"}}
""")


df = pd.read_csv(temp, sep=r' - (?={)', engine='python',header=None)
df.rename({0:'date',1:'info'},axis=1)

输出

                          date                              info
0  2019-08-15 00:00:06,430 0:0  {"info":{"name":"LTD - PUBLIC"}}

推荐阅读