AppDividend
Latest Code Tutorials

Pandas DataFrame size Property in Python

0

Pandas DataFrame size property is used to get the number of items in the object. It returns the number of rows if Series. Otherwise, if DataFrame, then it returns the number of rows times the number of columns. Pandas library is robust and powerful, which helps us to work on different datasets with ease.

Pandas .size, .shape, and .ndim are used to return size, shape, and dimensions of DataFrames and Series.

Syntax

DataFrame.size

Return Value

The size property returns the size of the DataFrame, i.e., the number of elements of the DataFrame.

Example program on pandas.DataFrame.size

Write a program to show the working of pandas.DataFrame.size.

import pandas as pd

data = pd.Series({'1st': 1, '2nd': 2, '3rd': 3, '4th': 4})
print(data, '\n')
print('Size = ', data.size)

Output

1st    1
2nd    2
3rd    3
4th    4
dtype: int64

Size =  4

Here in the above program, we can see that we have created a series and used the size to display the number of elements in the Series that is 4 in the case. 

For clarity, we have also printed the Series.

Example 2: Create a DataFrame with multiple values and show the corresponding size.

See the following code.

import pandas as pd

df = pd.DataFrame(
    {'1st': [1, 2], '2nd': [3, 4], '3rd': [5, 6], '4th': [7, 8]})
print(df, '\n')
print('Size = ', df.size)

Output

 1st  2nd  3rd  4th
0    1    3    5    7
1    2    4    6    8

Size =  8

Here we can see that we have must multiple values in different rows and got the output for the size of that DataFrame.

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

The DataFrame.size returns the size of the DataFrame/Series, which is equivalent to the total number of items. That is rows x columns.

The DataFrame.size returns the tuple of shape (Rows, columns) of DataFrame/Series.

The  DataFrame.ndim returns dimension of DataFrame/Series. 1 for one dimension (Series), 2 for two-dimension (DataFrame).

In this example, the output from size and shape is stored first. Since .size returns the total number of elements, it is compared by multiplying rows and columns returned by the shape method. After that dimension of DataFrame and Series is also checked using .ndim.

import pandas as pd

df = pd.DataFrame(
    {'1st': [1, 2], '2nd': [3, 4], '3rd': [5, 6], '4th': [7, 8]})
print(df, '\n')
print('Size = ', df.size)
print('Dimension = ', df.ndim)
print('Shape = ', df.shape)

Output

   1st  2nd  3rd  4th
0    1    3    5    7
1    2    4    6    8

Size =  8
Dimension =  2
Shape =  (2, 4)

From the output, you can see that rows x columns from .shape returns tuple (2, 4), and the size is 8.
Also, ndim for DataFrame is 2.

See also

Pandas DataFrame columns

Pandas DataFrame set_index()

Pandas DataFrame reset_index()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.