Pandas DataFrame.shape
Pandas DataFrame.shape
The DataFrame.shape
property in pandas is used to retrieve the dimensions of a DataFrame. It returns a tuple containing the number of rows and columns in the DataFrame.
Syntax
The syntax for accessing the shape
property is:
DataFrame.shape
Here, DataFrame
refers to the pandas DataFrame whose dimensions are being accessed.
Returns
A tuple of two integers:
- The first integer represents the number of rows.
- The second integer represents the number of columns.
Examples
Getting the Shape of a DataFrame
You can use the shape
property to get the number of rows and columns in a DataFrame.
Python Program
import pandas as pd
# Create a DataFrame
data = {
'Name': ['Arjun', 'Ram', 'Priya'],
'Age': [25, 30, 35],
'Salary': [70000.5, 80000.0, 90000.0]
}
df = pd.DataFrame(data)
# Get the shape of the DataFrame
print("Shape of the DataFrame:")
print(df.shape)
Output
Shape of the DataFrame:
(3, 3)
Using the Shape to Access Rows and Columns
You can use the shape
property to dynamically access rows and columns.
Python Program
import pandas as pd
# Create a DataFrame
data = {
'Name': ['Arjun', 'Ram', 'Priya'],
'Age': [25, 30, 35],
'Salary': [70000.5, 80000.0, 90000.0]
}
df = pd.DataFrame(data)
# Use shape to access the number of rows and columns
num_rows, num_columns = df.shape
print("Number of Rows:", num_rows)
print("Number of Columns:", num_columns)
Output
Number of Rows: 3
Number of Columns: 3
Working with an Empty DataFrame
For an empty DataFrame, the shape
property returns (0, 0)
if there are no rows and columns.
Python Program
import pandas as pd
# Create an empty DataFrame
df_empty = pd.DataFrame()
# Get the shape of the empty DataFrame
print("Shape of the Empty DataFrame:")
print(df_empty.shape)
Output
Shape of the Empty DataFrame:
(0, 0)
Filtering Data and Checking Shape
You can use the shape
property to check the size of a DataFrame after filtering rows.
Python Program
import pandas as pd
# Create a DataFrame
data = {
'Name': ['Arjun', 'Ram', 'Priya'],
'Age': [25, 30, 35],
'Salary': [70000.5, 80000.0, 90000.0]
}
df = pd.DataFrame(data)
# Filter rows where Age > 25
filtered_df = df[df['Age'] > 25]
# Get the shape of the filtered DataFrame
print("Shape of the Filtered DataFrame:")
print(filtered_df.shape)
Output
Shape of the Filtered DataFrame:
(2, 3)
Summary
In this tutorial, we explored the DataFrame.shape
property in pandas. Key points include:
- Using
shape
to get the dimensions of a DataFrame - Understanding its usage for dynamic operations
- Working with empty or filtered DataFrames
The DataFrame.shape
property is a quick and efficient way to understand the size of your data and its structure.