Skip to content
Related Articles

Related Articles

Count the number of rows and columns of a Pandas dataframe
  • Last Updated : 28 Jul, 2020

Pandas allow us to get the shape of the dataframe by counting the numbers of rows and columns in the dataframe. You can try various approaches to get the number of rows and columns of the dataframe. All of them have been discussed below.

Example: Let’s take an example of a dataframe which consists of data of exam result of students.

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing pandas 
import pandas as pd
result_data = {'name': ['Katherine', 'James', 'Emily',
                        'Michael', 'Matthew', 'Laura'],
        'score': [98, 80, 60, 85, 49, 92],
        'age': [20, 25, 22, 24, 21, 20],
        'qualify_label': ['yes', 'yes', 'no',
                          'yes', 'no', 'yes']}
  
# creating dataframe
df = pd.DataFrame(result_data, index = None)
  
# computing number of rows
rows = len(df.axes[0])
  
# computing number of columns
cols = len(df.axes[1])
  
print(df)
print("Number of Rows: ", rows)
print("Number of Columns: ", cols)

chevron_right


Output :

Example: Let’s take an example of a dataframe that consists of data on product sales.

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing pandas 
import pandas as pd
  
# creating dataframe
df = pd.DataFrame({'Product' : ['Carrots', 'Broccoli', 'Banana'
                                'Banana', 'Beans', 'Orange',
                                'Broccoli', 'Banana'],
                   'Category' : ['Vegetable', 'Vegetable', 'Fruit'
                                 'Fruit', 'Vegetable', 'Fruit'
                                 'Vegetable', 'Fruit'],
                   'Quantity' : [8, 5, 3, 4, 5, 9, 11, 8],
                   'Amount' : [270, 239, 617, 384, 626, 610, 62, 90]})
  
print(df)
  
# getting number of rows
print("Number of Rows: ", len(df.axes[0]))
  
# getting number of columns
print("Number of Columns: ", len(df.axes[1]))

chevron_right


Output :



Example: Here, we will try a different approach for calculating rows and columns of a dataframe of imported csv file.

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing pandas
import pandas as pd
  
# importing csv file
  
print(df.head())
  
# obtaining the shape
print("shape of dataframe", df.shape)
  
# obtaining the number of rows
print("number of rows : ", df.shape[0])
  
# obtaining the number of columns
print("number of columns : ", df.shape[1])

chevron_right


Output :

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :