【问题标题】:Python code to reads a csv file and print rows at even positions [duplicate]Python代码读取csv文件并在偶数位置打印行[重复]
【发布时间】:2021-05-30 21:51:07
【问题描述】:
  • 我有一个 CSV 文件。

  • 如何读取特定行?

  • 我想读取偶数位置的行?

import csv
with open('source.csv','rt')as f:
  data = csv.reader(f)
  for row in data:
        print(row)

【问题讨论】:

标签: python python-3.x csv


【解决方案1】:

给你:

import csv

even_rows = []
# reading the csv
with open("file.csv", "r+") as csv_file:
    # reading all lines
    lines = csv.reader(csv_file, delimiter=",")
    
    # extracting only even lines
    for i, line in zip(range(lines.line_num), lines):
        if i % 2 == 0:
            even_rows.append(line)

# printing output
for row in even_rows:
    print(row)

【讨论】:

    【解决方案2】:
    import pandas as pd
    
    dataframe = pd.read_csv('your_file')
    dataframe_even_rows = dataframe.iloc[::2]
    

    【讨论】:

      【解决方案3】:

      扩展 Adrien 提供的解决方案。

      import pandas as pd
      n = 1   #Number of rows you want to skip
      dataframe = pd.read_csv('your_file')
      dataframe_even_rows = dataframe.iloc[::(n+1)]
      dataframe_specific_row = dataframe.iloc[2] #Specific lines: read third line(index start at 0)
      

      【讨论】:

        猜你喜欢
        • 2017-12-01
        • 2019-04-29
        • 2017-05-12
        • 1970-01-01
        • 1970-01-01
        • 2019-08-06
        • 1970-01-01
        • 2013-01-21
        • 2020-11-03
        相关资源
        最近更新 更多