Python Pandas - Read data from a CSV file and print the 'product' column value that matches 'Car' for the first ten rows

When working with CSV data in Pandas, you often need to filter specific rows based on column values. This tutorial shows how to read a CSV file and filter rows where the 'product' column matches 'Car' from the first ten rows.

We'll use the 'products.csv' file which contains 100 rows and 8 columns with product information.

Sample Data Structure

The products.csv file contains the following structure ?

Rows: 100 Columns: 8
id   product   engine   avgmileage   price   height_mm   width_mm   productionYear
1 2   Car       Diesel        21      16500      1530        1735         2020
4 5   Car       Gas           18      17450      1530        1780         2018
5 6   Car       Gas           19      15250      1530        1790         2019
8 9   Car       Diesel        23      16925      1530        1800         2018

Using iloc with Column Index

This method uses positional indexing to access the product column ?

import pandas as pd

# Read CSV file
df = pd.read_csv('products.csv')
print("Rows:", df.shape[0], "Columns:", df.shape[1])

# Get first 10 rows
df1 = df.iloc[0:10, :]

# Filter rows where product column (index 1) equals 'Car'
result = df1[df1.iloc[:, 1] == 'Car']
print(result)

Using head() with Column Name

This method uses column names for more readable code ?

import pandas as pd

# Read CSV file
df = pd.read_csv('products.csv')
print("Rows:", df.shape[0], "Columns:", df.shape[1])

# Get first 10 rows using head()
df1 = df.head(10)

# Filter rows where product column equals 'Car'
result = df1[df1['product'] == 'Car']
print(result)

Expected Output

Both methods will produce the same output ?

Rows: 100 Columns: 8
id   product   engine   avgmileage   price   height_mm   width_mm   productionYear
1 2   Car       Diesel        21      16500      1530        1735         2020
4 5   Car       Gas           18      17450      1530        1780         2018
5 6   Car       Gas           19      15250      1530        1790         2019
8 9   Car       Diesel        23      16925      1530        1800         2018

Comparison

Method Pros Cons
iloc with index Works even if column names change Less readable, requires knowing column position
Column name filtering More readable and intuitive Breaks if column name changes

Conclusion

Use column name filtering for better readability and maintainability. The head() method is more intuitive than iloc for getting the first n rows. Both approaches effectively filter CSV data based on specific criteria.

Updated on: 2026-03-25T16:43:32+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements