【问题标题】:Is it possible to use read_csv to read only specific lines?是否可以使用 read_csv 仅读取特定行?
【发布时间】:2012-05-29 20:34:38
【问题描述】:

我有一个如下所示的 csv 文件:

TEST  
2012-05-01 00:00:00.203 ON 1  
2012-05-01 00:00:11.203 OFF 0  
2012-05-01 00:00:22.203 ON 1  
2012-05-01 00:00:33.203 OFF 0  
2012-05-01 00:00:44.203 OFF 0  
TEST  
2012-05-02 00:00:00.203 OFF 0  
2012-05-02 00:00:11.203 OFF 0  
2012-05-02 00:00:22.203 OFF 0  
2012-05-02 00:00:33.203 OFF 0  
2012-05-02 00:00:44.203 ON 1  
2012-05-02 00:00:55.203 OFF 0  

并且无法摆脱"TEST" 字符串。

是否可以检查一行是否以日期开头并只读那些日期?

【问题讨论】:

    标签: python csv pandas


    【解决方案1】:

    当你从csv.reader得到row,并且当你可以确定第一个元素是一个字符串时,那么你可以使用

    if not row[0].startswith('TEST'):
        process(row)
    

    【讨论】:

      【解决方案2】:

      http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_csv.html?highlight=read_csv#pandas.io.parsers.read_csv

      skiprows : 类列表或整数 要跳过的行号(0-indexed)或要跳过的行数(int)

      传递 [0, 6] 以跳过带有“TEST”的行。

      【讨论】:

      • 恐怕他知道这些线条的样子,而不是它们的索引。
      【解决方案3】:
      from cStringIO import StringIO
      import pandas
      
      s = StringIO()
      with open('file.csv') as f:
          for line in f:
              if not line.startswith('TEST'):
                  s.write(line)
      s.seek(0) # "rewind" to the beginning of the StringIO object
      
      pandas.read_csv(s) # with further parameters…
      

      【讨论】:

        【解决方案4】:

        另一个选择,因为我也遇到了这个问题:

        import pandas as pd
        import subprocess
        grep = subprocess.check_output(['grep', '-n', '^TITLE', filename]).splitlines()
        bad_lines = [int(s[:s.index(':')]) - 1 for s in grep]
        df = pd.read_csv(filename, skiprows=bad_lines)
        

        它比@eumiro 的便携性差(阅读:可能在 Windows 上不起作用)并且需要两次读取文件,但优点是您不必将整个文件内容存储在内存中。

        你当然可以做与 Python 中的 grep 相同的事情,但它可能会更慢。

        【讨论】:

          猜你喜欢
          • 2015-07-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-04-18
          • 1970-01-01
          • 2017-01-27
          相关资源
          最近更新 更多