pandas read_csv不服从正则表达式sep

时间:2017-06-27 18:28:25

标签: python csv pandas

数据

from io import StringIO
import pandas as pd

s = '''ID,Level,QID,Text,ResponseID,responseText,date_key,last
375280046,S,D3M,Which is your favorite?,D5M0,option 1,2012-08-08 00:00:00,ynot
375280046,S,D3M,How often? (at home, at work, other),D3M0,Work,2010-03-31 00:00:00,okkk
375280046,M,A78,Do you prefer a, b, or c?,A78C,a,2010-03-31 00:00:00,abc
376918925,M,A78,Which ONE (select only one),A78E,Milk,2004-02-02 00:00:00,launch Wed., '''

df = pd.read_csv(StringIO(s), sep=r',(?!\s)')

问题:我问了一个问题here。我遇到了一个新问题。请注意,在最后一行的末尾,它是一个逗号和一个空格。 sep=r',(?!\s)'中的正则表达式应该忽略后跟空格的逗号。

问题:有没有办法按字面launch Wed.,读取最后一列,其中逗号不是分隔符/分隔符,但实际上是{{1}中的逗号列文字 - 仅使用last

错误

pd.read_csv

预期/期望的输出

ValueError: Expected 8 fields in line 5, saw 9. Error could possibly be due to quotes being ignored when a multi-char delimiter is used.

2 个答案:

答案 0 :(得分:4)

让我们看看这个SO Post

使用上面解释的正则表达式r',(?=\S)'

from io import StringIO
import pandas as pd

s = '''ID,Level,QID,Text,ResponseID,responseText,date_key,last
375280046,S,D3M,Which is your favorite?,D5M0,option 1,2012-08-08 00:00:00,ynot
375280046,S,D3M,How often? (at home, at work, other),D3M0,Work,2010-03-31 00:00:00,okkk
375280046,M,A78,Do you prefer a, b, or c?,A78C,a,2010-03-31 00:00:00,abc
376918925,M,A78,Which ONE (select only one),A78E,Milk,2004-02-02 00:00:00,launch Wed., '''

df = pd.read_csv(StringIO(s), sep=r',(?=\S)')

输出:

              ID                                 Level   QID      Text  \
375280046 S  D3M               Which is your favorite?  D5M0  option 1   
          S  D3M  How often? (at home, at work, other)  D3M0      Work   
          M  A78             Do you prefer a, b, or c?  A78C         a   
376918925 M  A78           Which ONE (select only one)  A78E      Milk   

                ResponseID  responseText  date_key          last  
375280046 S  2012-08-08 00             0         0          ynot  
          S  2010-03-31 00             0         0          okkk  
          M  2010-03-31 00             0         0           abc  
376918925 M  2004-02-02 00             0         0  launch Wed.,  

答案 1 :(得分:2)

在尝试识别分隔符之前,

read_csv似乎正在从字符串末尾剥离空格。这可以通过修改正则表达式以检查在文件结尾之前标识的逗号来解决:

pd.read_csv(StringIO(s), sep=r',(?!\s|\Z)', engine='python')
Out[347]: 
          ID Level  QID                                  Text ResponseID  \
0  375280046     S  D3M               Which is your favorite?       D5M0   
1  375280046     S  D3M  How often? (at home, at work, other)       D3M0   
2  375280046     M  A78             Do you prefer a, b, or c?       A78C   
3  376918925     M  A78           Which ONE (select only one)       A78E   

  responseText             date_key          last  
0     option 1  2012-08-08 00:00:00          ynot  
1         Work  2010-03-31 00:00:00          okkk  
2            a  2010-03-31 00:00:00           abc  
3         Milk  2004-02-02 00:00:00  launch Wed.,