CBSE CS and IP

CBSE Class 11 & 12 Computer Science and Informatics Practices Python Materials, Video Lecture

sum() Method of DataFrame

< Back


Use:
Return the sum of the values for the requested axis.
Prototype:
<DataFrame_Obj>.sum ( [axis = 0 or ‘rows’ | 1 or ‘columns’ ] )

import pandas as pd

df = pd.DataFrame({
    'a': [4, 5, 6, 7],
    'b': [10, 20, 30, 40],
    'c': [100, 50, -30, -50]
})

print(df)

   a   b    c
0  4  10  100
1  5  20   50
2  6  30  -30
3  7  40  -50
The summation functions sum() is a descriptive function which is used to give the sum of rows or columns as specifies in axis. If axis parameter is not provided the default axis is 0 or ‘rows’. That means by default sum of rows will be provided.

This function retuens the sum of each all the elemnets in the form of Series.

Note:- Here the axis='rows' menas sum of all the elemnets in different rows, not in a sing row vise-versa for axis='columns'.

Default axis is rows:
print(df.sum())
a     22
b    100
c     70
dtype: int64

Using axis = 'rows' will provide the same output as above. You can use axis = 0 also.


print(df.sum(axis = 'rows'))
a     22
b    100
c     70
dtype: int64
Using axis = 'columns' or axis = 1. You can see the sum of all the columns has been printed with row indexes.
print(df.sum(axis = 'columns'))
0    114
1     75
2      6
3     -3
dtype: int64

No comments:

Post a Comment