Returning the number of array dimension of a DataFrame in Pandas

Overview

The DataFrame.ndim attribute in Pandas library returns the number (an int) representing the number of array dimensions of a given series or DataFrame.

Syntax

The DataFrame.ndim attribute takes the following syntax:

DataFrame.ndim
Syntax for the DataFrame.ndim attribute in Pandas

Parameter value

The DataFrame.ndim being an attribute takes no parameter value.

Return value

The DataFrame.ndim attribute returns an int value 1 if the input data is series and a value of 2 if otherwise.

Example

import pandas as pd
# creating a dataframe
a = pd.DataFrame({'AGE': [ 20, 29],
'HEIGHT': [94, 170],
'WEIGHT': [80, 115]})
# creating a series
b = pd.Series({'a': 1, 'b': 2, 'c': 3})
# implemnting the DataFrame.ndim attribute
print(a.ndim)
print(b.ndim)

Explanation

  • Line 1: We import the pandas module.
  • Line 4–6: We create a data frame, a.
  • Line 9: We create a series, b.
  • Line 12: We obtain the number of array dimension of a and print the result to the console.
  • Line 13: We obtain the number of array dimension of b and print the result to the console.

Free Resources