Python - Sum only specific rows of a Pandas Dataframe


To sum only specific rows, use the loc() method. Mention the beginning and end row index using the : operator. Using loc(), you can also set the columns to be included. We can display the result in a new column.

At first, let us create a DataFrame. We have Product records in it, including the Opening and Closing Stock −

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

Sum of some rows i.e. 1st two rows. Column names also mentioned in the loc() i.e. Opening_Stock and Closing_Stock. We are displaying result in a new column “Sum_Result” −

dataFrame['Sum_Result'] = dataFrame.loc[0 : 1,["Opening_Stock" , "Closing_Stock"]].sum(axis = 1)

Example

Following is the complete code −

import pandas as pd

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

print"DataFrame...\n",dataFrame

# sum of some rows
# Column names also mentioned in the loc() i.e. Opening_Stock and Closing_Stock
# displaying result in a new column Sum_Result
dataFrame['Sum_Result'] = dataFrame.loc[0 : 1,["Opening_Stock" , "Closing_Stock"]].sum(axis = 1)
print"\nSumming some rows...\n",dataFrame

Output

This will produce the following output −

DataFrame...
   Closing_Stock   Opening_Stock   Product
0           200             300    SmartTV
1           500             700    ChromeCast
2          1000            1200    Speaker
3           900            1500    Earphone

Summing some rows...
   Closing_Stock   Opening_Stock   Product   Sum_Result
0           200             300    SmartTV       500.0
1           500             700    ChromeCast   1200.0
2          1000            1200    Speaker         NaN
3           900            1500    Earphone        NaN

Updated on: 15-Sep-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements