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


Assume, you have ‘products.csv’ file and the result for a number of rows and columns and ‘product’ column value matches ‘Car’ for the first ten rows are −

Download the products.csv file here.

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

We have two different solutions for this problem.

Solution 1

df = pd.read_csv('products.csv ')
  • Print the number of rows = df.shape[0] and columns = df.shape[1]

  • Set df1 to filter first ten rows from df using iloc[0:10,:]

df1 = df.iloc[0:10,:]
  • Calculate the product column values matches to the car using df1.iloc[:,1]

Here, the product column index is 1, and finally print the data

df1[df1.iloc[:,1]=='Car']

Example

Let’s check the following code to get a better understanding −

import pandas as pd
df = pd.read_csv('products.csv ')
print("Rows:",df.shape[0],"Columns:",df.shape[1])
df1 = df.iloc[0:10,:]
print(df1[df1.iloc[:,1]=='Car'])

Solution 2

df = pd.read_csv('products.csv ')
  • Print the number of rows = df.shape[0] and columns = df.shape[1]

  • Take first ten rows using df.head(10) and assign to df

df1 = df.head(10)
  • Take product column values matches to Car using below method

df1[df1['product']=='Car']

Example

Now, let’s check its implementation to get a better understanding −

import pandas as pd
df = pd.read_csv('products.csv ')
print("Rows:",df.shape[0],"Columns:",df.shape[1])
df1 = df.head(10)
print(df1[df1['product']=='Car'])

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

Updated on: 17-Feb-2021

690 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements