What is ndim in pandas DataFrame?


The ndim is an attribute in the pandas DataFrame which is used to get the integer/number representation of dimensions of the given DataFrame object.

As we know, the pandas DataFrame is a two-dimensional data structure that is used to store the data in a tabular format. Regardless of the number of rows and columns lengths or type of data the dimensions of the DataFrame do not affect.

The output for the ndim property of pandas DataFrame is always 2.

Example 1

In this following example, we have applied the ndim attribute to the pandas DataFrame object “df”, this DataFrame is created with a single column “Col1”.

# importing pandas packages
import pandas as pd

L = list('ABCDEFGH')

# creating pandas DataFrame
df = pd.DataFrame(L, columns=['col1'])

print('DataFrame:')
print(df)

# apply ndim property to get the dimensions
print('Result:', df.ndim)

Output

The output is as follows −

DataFrame:
  col1
0    A
1    B
2    C
3    D
4    E
5    F
6    G
7    H

Result: 2

In the above output block, the value 2 represents the dimensions of the given DataFrame.

Example 2

Let's use another pandas DataFrame object and apply the ndim attribute to get the dimensions.

# importing pandas package
import pandas as pd

# create a Pandas DataFrame
df = pd.DataFrame({'Country':['Brazil','Canada','New Zealand','Iceland', 'India', 'Sri Lanka', 'United States'],
'Capital': [ 'Belmopan','Ottawa','Wellington','Reykjavik', 'New Delhi','Colombo', 'Washington D.C']})

print("DataFrame:")
print(df)

# apply ndim property to get the dimensions
print('Result:', df.ndim)

Output

The output is as follows −

DataFrame:
       Country         Capital
0       Brazil        Belmopan
1       Canada          Ottawa
2  New Zealand      Wellington
3      Iceland       Reykjavik
4        India       New Delhi
5     Sri Lanka        Colombo
6 United States Washington D.C
Result: 2

For this example also the ndim attribute returned 2for the given DataFrame.

Updated on: 08-Mar-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements