Saturday, November 16, 2024
Google search engine
HomeLanguagesPandas df.size, df.shape and df.ndim Methods

Pandas df.size, df.shape and df.ndim Methods

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas size, shape, and ndim methods are used to return the size, shape, and dimensions of data frames and series.

Dataset Used

To download the data set used in the following example, click here. In the following examples, the data frame used contains data from some NBA players.

Pandas Size Function

The size property is used to get an int representing the number of elements in this object and Return the number of rows if Series. Otherwise, return the number of rows times the number of columns if DataFrame.

Pandas df. size Syntax

Syntax: dataframe.size
Return : Returns size of dataframe/series which is equivalent to total number of elements. That is rows x columns.

Example

This code uses pandas to read “nba.csv” and It then calculates and prints the total number of elements (size) in the DataFrame.

Python3




# importing pandas module
import pandas as pd
 
# importing csv file
data = pd.read_csv("nba.csv")
 
# dataframe.size
size = data.size
 
# printing size
print("Size = {}".format(size))


Output:

Size = 4122

Pandas Shape Function

The shape property is used to get a tuple representing the dimensionality of the Pandas DataFrame.

Pandas df.shape Syntax

Syntax: dataframe.shape
Return : Returns tuple of shape (Rows, columns) of dataframe/series

Example

This code uses pandas to read “nba.csv” and It then calculates and prints the shape of the DataFrame, which includes the number of rows and columns.

Python3




# importing pandas module
import pandas as pd
 
# importing csv file
data = pd.read_csv("nba.csv")
 
# using dataframe.shape
shape = data.shape
 
# printing shape
print("Shape = {}".format(shape))


Output:

Shape = (458, 9)

Pandas ndim Function

The ndim property is used to get an int representing the number of axes/array dimensions and Return 1 if Series. Otherwise, return 2 if DataFrame.

Pandas df.ndim Syntax

Syntax: dataframe.ndim
Return : Returns dimension of dataframe/series. 1 for one dimension (series), 2 for two dimension (dataframe)

Example

This code uses pandas to read “nba.csv”. Calculates and prints the number of dimensions (ndim) for both the DataFrame and a specific column (“Salary”) treated as a Series within the DataFrame.

Python3




# importing pandas module
import pandas as pd
 
# reading csv file
data = pd.read_csv("nba.csv")
 
# dataframe.ndim
df_ndim = data.ndim
 
# series.ndim
series_ndim = data["Salary"].ndim
 
# printing ndim
print("ndim of dataframe = {}\nndim of series ={}".
      format(df_ndim, series_ndim))


Output:

ndim of dataframe = 2
ndim of series =1

RELATED ARTICLES

Most Popular

Recent Comments