Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python代码读取csv文件并在偶数位置打印行_Python_Python 3.x_Csv - Fatal编程技术网

Python代码读取csv文件并在偶数位置打印行

Python代码读取csv文件并在偶数位置打印行,python,python-3.x,csv,Python,Python 3.x,Csv,我有一个CSV文件 如何读取特定行 我想读偶数位置的行 给你: 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

我有一个CSV文件

  • 如何读取特定行

  • 我想读偶数位置的行

  • 给你:

    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)
    

    扩展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)
    

    堆栈溢出不是免费的编程服务。向我们展示您已经拥有的代码!这回答了你的问题吗?
    import pandas as pd
    
    dataframe = pd.read_csv('your_file')
    dataframe_even_rows = dataframe.iloc[::2]
    
    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)