How to get the length, size, and shape of a series in Pandas?

PandasServer Side ProgrammingProgramming

There are several ways to get the number of elements present in a pandas Series object. And the class pandas series constructor provides you several attributes and methods to determine the features of the Series object.

In the following example, we will learn about the size and shape attributes of the pandas Series object. The size attribute will return an integer value representing the count of the total elements present in a Series object, which works similarly to the python length function.

The shape attribute will return a tuple with two elements in it, those two elements are integer values representing the rows and columns count of a pandas data structure object. Here the pandas Series is a one-Dimensional pandas data structure object with labeled indices, hence the output for the shape attribute will return you a tuple with a single integer element representing the rows count of a pandas Series object.

Example

# importing pandas packages
import pandas as pd

# creating pandas Series object
series = pd.Series(list('ABCDEFGH'))
print(series)

# to get length of the series
print('Length of series:',len(series))

print('Size of the Series:', series.size)

print('The shape of series:',series.shape)

Explanation

Here we have created a simple series object with string data, and the data is A, B, C, D, E, F, G, H, with the index values 0, 1, 2 to 7.

By using the python length function we can get the length of the Series object, as well as size and shape attributes will return the count of elements and dimension of the series.

Output

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

Length of series: 8
Size of the Series: 8
The shape of series: (8,)

The integer and Alphabet columns are the representation of the series object output and the data type of this series is an object data type. And we can see the output of length function, size attribute, and shape attribute in the above output block.

Example

# importing pandas packages
import pandas as pd

# creating pandas Series object
series = pd.Series({'B':'black', 'W':'white', 'R':'red', 'G':'green'})
print(series)

# to get length of the series
print('Length of series:',len(series))

print('Size of the Series:', series.size)

print('The shape of series:',series.shape)

Explanation

The series object was created by using a dictionary with keys and value pairs, in this example we verified the length, size and shape of the series object by using pandas series attributes.

Output

B   black
W   white
R     red
G   green
dtype: object
Length of series: 4
Size of the Series: 4
The shape of series: (4,)

The length, size and shape of our series object can be seen in the above output block.

raja
Published on 17-Nov-2021 07:35:41
Advertisements