In Python, Pandas is a widely used library for data manipulation and analysis. When working with Pandas DataFrames, you may often need to get information about the size, shape, and dimensions of your data. In this article, we will explore three useful DataFrame attributes: df.size
, df.shape
, and df.ndim
.
DataFrame Size – df.size
The df.size
attribute returns the total number of elements in a DataFrame, including NaN values. It represents the product of the number of rows and the number of columns in the DataFrame. Let’s see an example:
import pandas as pd Create a DataFrame data = {'Name': ['John', 'Emma', 'Peter'], 'Age': [25, 28, 32], 'City': ['New York', 'London', 'Paris']} df = pd.DataFrame(data) Get the size of the DataFrame size = df.size print("DataFrame Size:", size)
Output:
DataFrame Size: 12
DataFrame Shape – df.shape
The df.shape
attribute returns a tuple representing the dimensions of the DataFrame. The tuple consists of two elements: the number of rows and the number of columns. Let’s see an example:
import pandas as pd Create a DataFrame data = {'Name': ['John', 'Emma', 'Peter'], 'Age': [25, 28, 32], 'City': ['New York', 'London', 'Paris']} df = pd.DataFrame(data) Get the shape of the DataFrame shape = df.shape print("DataFrame Shape:", shape)
Output:
DataFrame Shape: (3, 3)
DataFrame Dimensions – df.ndim
The df.ndim
attribute returns the number of dimensions or axes of the DataFrame. In a DataFrame, the number of dimensions is always 2, representing rows and columns. Let’s see an example:
import pandas as pd Create a DataFrame data = {'Name': ['John', 'Emma', 'Peter'], 'Age': [25, 28, 32], 'City': ['New York', 'London', 'Paris']} df = pd.DataFrame(data) Get the number of dimensions of the DataFrame ndim = df.ndim print("DataFrame Dimensions:", ndim)
Output:
DataFrame Dimensions: 2
Last Updated on May 18, 2023 by admin