Python - Summing all the rows of a Pandas Dataframe

PythonServer Side ProgrammingProgramming

To sum all the rows of a DataFrame, use the sum() function and set the axis value as 1. The value axis 1 will add the row values.

At first, let us create a DataFrame. We have Opening and Closing Stock columns in it

dataFrame = pd.DataFrame({"Opening_Stock": [300, 700, 1200, 1500],"Closing_Stock": [200, 500, 1000, 900]})

Finding sum of row values. Axis is set 1 to add row values

dataFrame = dataFrame.sum(axis = 1)

Example

Following is the complete code

import pandas as pd

dataFrame = pd.DataFrame({"Opening_Stock": [300, 700, 1200, 1500],"Closing_Stock": [200, 500, 1000, 900]})

print"DataFrame...\n",dataFrame

# finding sum of row values
# axis is set 1 to add row values
dataFrame = dataFrame.sum(axis = 1)
print"\nSumming rows...\n",dataFrame

Output

This will produce the following output

DataFrame...
   Closing_Stock   Opening_Stock
0          200             300
1          500             700
2         1000            1200
3          900            1500

Summing rows...
0      500
1     1200
2     2200
3     2400
dtype: int64
raja
Published on 14-Sep-2021 08:24:49
Advertisements