【问题标题】:Pandas: Error tokenizing data--when using glob.globPandas:错误标记数据——使用 glob.glob 时
【发布时间】:2016-05-25 14:22:18
【问题描述】:

我正在使用以下代码连接我从here 下载的几个文件(候选主文件);但也可以在这里找到:

https://github.com/108michael/ms_thesis/blob/master/cn06.txt
https://github.com/108michael/ms_thesis/blob/master/cn08.txt
https://github.com/108michael/ms_thesis/blob/master/cn10.txt
https://github.com/108michael/ms_thesis/blob/master/cn12.txt
https://github.com/108michael/ms_thesis/blob/master/cn14.txt

import numpy as np
import pandas as pd
import glob


df = pd.concat((pd.read_csv(f, header=None, names=['feccandid','candname',\
'party','date', 'state', 'chamber', 'district', 'incumb.challeng', \
'cand_status', '1', '2','3','4', '5', '6'  ], usecols=['feccandid', \
'party', 'date', 'state', 'chamber'])for f in glob.glob\
        ('/home/jayaramdas/anaconda3/Thesis/FEC/cn_data/cn**.txt')))

我收到以下错误:

CParserError: Error tokenizing data. C error: Expected 2 fields in line 58, saw 4

有人知道吗?

【问题讨论】:

  • 当您在一个文件上使用read_csv 时,数据框看起来是否符合预期?您可能需要将delimiter = "|" 传递给read_csv 函数。
  • 我刚刚尝试只读取一个文件并使用 ?sep='|'; and then after your comment ^ I tried using delimiter = '|'` 并且效果很好。我再次尝试了整个操作并解决了问题!谢谢你的线索!°
  • 很高兴它成功了!我添加它作为答案,以防其他人有同样的问题。

标签: python pandas concatenation glob


【解决方案1】:

pd.read_csv 的默认分隔符是逗号 ,。由于所有候选人的姓名都以Last, First 格式列出,因此 pandas 会读取两列:逗号之前的所有内容和逗号之后的所有内容。在其中一个文件中,有额外的逗号,导致 pandas 假设有更多列。那是解析器错误。

要使用| 而不是, 作为分隔符,只需将您的代码更改为使用关键字delimiter="|"sep="|"。从docs可以看出delimiter和sep是同一个关键字的别名。

新代码:

df = pd.concat((pd.read_csv(f, header=None, delimiter="|", names=['feccandid','candname',\
'party','date', 'state', 'chamber', 'district', 'incumb.challeng', \
'cand_status', '1', '2','3','4', '5', '6'  ], usecols=['feccandid', \
'party', 'date', 'state', 'chamber'])for f in glob.glob\
    ('/home/jayaramdas/anaconda3/Thesis/FEC/cn_data/cn**.txt')))

【讨论】:

    【解决方案2】:
    import numpy as np
    import pandas as pd
    import glob
    
    
    df = pd.concat((pd.read_csv(f, header=None, names=['feccandid','candname', \
        'party','date', 'state', 'chamber', 'district', 'incumb.challeng', \
        'cand_status', '1', '2','3','4', '5', '6'  ],sep='|', \
        usecols=['feccandid', 'party', 'date', 'state', 'chamber'] \
        )for f in glob.glob\
        (/home/jayaramdas/anaconda3/Thesis/FEC/cn_data/cn**.txt')))
    print len(df)
    

    【讨论】:

      猜你喜欢
      • 2013-08-05
      • 2016-08-23
      • 1970-01-01
      • 2019-08-06
      • 2020-02-03
      • 2021-10-03
      • 2019-06-18
      相关资源
      最近更新 更多