Python Pandas – How to use Pandas DataFrame Property: shape

PythonPandasServer Side ProgrammingProgramming

Write a Python program to read data from the products.csv file and print the number of rows and columns. Then print the ‘product’ column value matches ‘Car’ for first ten rows

Assume, you have ‘products.csv’ file and the result for number of rows and columns and ‘product’ column value matches ‘Car’ for 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 car using df1.iloc[:,1]

Here, 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'])

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

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']

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

Example

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
raja
Published on 27-Feb-2021 06:50:10
Advertisements