【问题标题】:How do you grab specific rows from csv file while avoiding others? [closed]您如何从 csv 文件中获取特定行,同时避免其他行? [关闭]
【发布时间】:2018-04-16 23:02:48
【问题描述】:

假设我的 csv 文件中有 100 行。

但是,我想要第 3-9 行和第 10-37 行。

基本上试图跳过某些行。我怎么能做到这一点?

【问题讨论】:

  • 欢迎来到 SO。不幸的是,这不是一个讨论论坛或教程。请花时间阅读How to Ask 和该页面上的其他链接。花一些时间与the Tutorial 练习示例。它将让您了解 Python 提供的帮助您解决问题的工具。

标签: python csv


【解决方案1】:

在我的第一个答案中,我向您展示了如何获取特定列,我的错。我误读了你的问题。为了获得特定的行,您可以使用列表推导。

desired_row_indexes = [1, 2, 3, 10, 11, 12] # You can also use ranges
desired_rows = [row for idx, row in enumerate(csv_document) if idx in desired_row_indexes]

这其实是duplicated

【讨论】:

    【解决方案2】:

    您可以使用 panda 包来解析 CSV 并跳过特定行。

    import pandas as pd    
    df = pd.read_csv('myfile.csv', skiprows='list with row number to skip')
    

    【讨论】:

      猜你喜欢
      • 2017-06-07
      • 2020-05-17
      • 2013-06-15
      • 2018-05-23
      • 2019-08-12
      • 1970-01-01
      • 2011-04-30
      • 1970-01-01
      相关资源
      最近更新 更多