How to Skip the Header Row When Reading a CSV File in Python?

Estimated read time 2 min read

When reading a CSV file in Python using the csv module or the pandas library, you can skip the header row (i.e., the first row of column labels) using different methods.

Using the csv module:

To skip the header row when reading a CSV file using the csv module, you can use the next() function to skip the first row before iterating over the remaining rows. Here’s an example:

import csv

with open('mydata.csv', 'r') as f:
    reader = csv.reader(f)
    next(reader)  # skip the header row
    for row in reader:
        print(row)

In this example, we use the csv.reader() function to create a reader object that can iterate over the rows of the CSV file. We use the next() function to skip the first row (i.e., the header row) before iterating over the remaining rows using a for loop.

Using the pandas library:

To skip the header row when reading a CSV file using the pandas library, you can use the skiprows parameter of the read_csv() function to skip the first row. Here’s an example:

import pandas as pd

df = pd.read_csv('mydata.csv', skiprows=1)
print(df)

In this example, we use the pd.read_csv() function to read the CSV file into a pandas DataFrame. We use the skiprows parameter to skip the first row (i.e., the header row). The resulting DataFrame does not include the header row.

Note that in both cases, skipping the header row assumes that the header row is the first row of the CSV file. If the header row is located at a different row index, you can adjust the row index accordingly.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply