+3 votes
in Programming Languages by (59.3k points)
What function should I use to find the total number of elements in a Pandas DataFrame?

1 Answer

0 votes
by (232k points)

To find the number of elements in a pandas DataFrame, you can use size. You can also use shape to find the number of rows and columns and then take their product to calculate the number of elements.

Approach 1:

>>> import pandas as pd
>>> df = pd.DataFrame({'A':[10,20,30], 'B':[11,22,33], 'C':[12,24,36], 'D':[13,26,39]})
>>> df
    A   B   C   D
0  10  11  12  13
1  20  22  24  26
2  30  33  36  39
>>> df.size
12

Approach 2:

>>> import pandas as pd
>>> df = pd.DataFrame({'A':[10,20,30], 'B':[11,22,33], 'C':[12,24,36], 'D':[13,26,39]})
>>> df
    A   B   C   D
0  10  11  12  13
1  20  22  24  26
2  30  33  36  39
>>> r,c = df.shape
>>> size = r*c
>>> size
12


...