【问题标题】:How to remove double quote from a csv file before reading it?如何在阅读之前从 csv 文件中删除双引号?
【发布时间】:2021-02-22 17:02:48
【问题描述】:

我收到以下错误:

pandas.errors.ParserError: '|'预计在 '"'

之后

原因是因为第一行有 '"' 不应该在那里:

"Name|Kind|Color|Price

我尝试了以下方法:

`pd.read_csv(filename, sep='|', usecols=fields, engine='python')`

这会产生上述错误。

pd.read_csv(filename, sep='|', usecols=fields, engine='python', quotechar='"', error_bad_lines=False)

这不起作用,因为它删除了我需要的整行,因为它是列标题。

有没有办法在不重写文件的情况下解决这个问题?也许将它读入一个字符串并删除'"',,但是我如何使用以下内容读取该字符串?

pd.read_csv(filename, sep='|', usecols=fields, engine='python')

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你明白这个问题。

    单独阅读第一行(见Ashwini Chaudhary's method) 获得该行后,删除双引号并使用分隔符拆分该行。

    # Initialize your separator and filename
    sep = '|'
    filename = 'some.csv'
    
    # Read the first line and remove the double quote
    
    with open(filename, newline='') as f:
      reader = csv.reader(f)
      row1 = next(reader)  
      cols = row1.replace('"','').split(sep)
    
    

    使用cols 列表,执行pandas.read_csv,跳过第一行(无标题行)并使用您刚刚提取的cols 列表指定列名。

    df = pd.read_csv(filename, 
                     sep=sep, 
                     skiprows=1, 
                     header=0, 
                     names=cols, 
                     engine='python')
    
    

    read_csv 假定您要使用第一行中通过分隔符定义的所有列。如果您只想使用子集,则需要调整 cols 列表并指定 use_cols

    【讨论】:

      【解决方案2】:

      我不完全确定您的问题,但给出了一个 csv 文件,例如:

      "Name|Kind|Color|Price
      alex|robot|braun|100$
      

      那么以下代码将删除任何前导“#”(如果存在):

      import pandas as pd
      import re
      
      
      pd.DataFrame([
          re.match(r'"*(?P<line>.*)', line)
          .group("line")
          .split("|")
          for line in open("tmp.csv").readlines()
      ])
      
      
      # 
      #       0      1      2      3
      # 0  Name   Kind  Color  Price
      # 1  alex  robot  braun   100$
      

      【讨论】:

        猜你喜欢
        • 2022-01-20
        • 2014-05-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-16
        • 2018-07-27
        • 2017-02-13
        相关资源
        最近更新 更多