Pandas DataFrame.ndim
Pandas DataFrame.ndim
The DataFrame.ndim property in pandas returns the number of dimensions of the DataFrame. Since a pandas DataFrame is inherently two-dimensional, this property always returns 2.
Syntax
The syntax for accessing the ndim property is:
DataFrame.ndimHere, DataFrame refers to the pandas DataFrame whose dimensionality is being accessed.
Returns
An integer indicating the number of dimensions of the DataFrame. For all DataFrames, this value is always 2.
Examples
Basic Usage of DataFrame.ndim
Use the ndim property to check the number of dimensions of a DataFrame.
Python Program
import pandas as pd
# Create a DataFrame
data = {
'Name': ['Arjun', 'Ram', 'Suresh'],
'Age': [25, 30, 35],
'Salary': [70000.5, 80000.0, 90000.0]
}
df = pd.DataFrame(data)
# Access the ndim property
print("Number of Dimensions:")
print(df.ndim)Output
Number of Dimensions:
2Using ndim with an Empty DataFrame
The ndim property also applies to empty DataFrames, and it will still return 2.
Python Program
import pandas as pd
# Create an empty DataFrame
empty_df = pd.DataFrame()
# Access the ndim property
print("Number of Dimensions of an Empty DataFrame:")
print(empty_df.ndim)Output
Number of Dimensions of an Empty DataFrame:
2Comparison with Other Pandas Objects
The ndim property can be used to check the dimensions of different pandas objects like Series or DataFrame.
Python Program
import pandas as pd
# Create a DataFrame
data = {
'Name': ['Arjun', 'Ram', 'Suresh'],
'Age': [25, 30, 35]
}
df = pd.DataFrame(data)
# Create a Series
series = pd.Series([10, 20, 30])
# Access the ndim property for both
print("Number of Dimensions in DataFrame:")
print(df.ndim)
print("Number of Dimensions in Series:")
print(series.ndim)Output
Number of Dimensions in DataFrame:
2
Number of Dimensions in Series:
1Summary
In this tutorial, we explored the DataFrame.ndim property in pandas. Key points include:
- The
ndimproperty returns the number of dimensions of a DataFrame, which is always2. - It applies to both regular and empty DataFrames.
- The
ndimproperty can be used to compare dimensions across different pandas objects like Series and DataFrame.
The DataFrame.ndim property is a simple yet effective way to verify the dimensionality of a DataFrame.