Evaluate Sum of Rows Using eval() Function in Python Pandas



The eval() function can also be used to evaluate the sum of rows with the specified columns. At first, let us create a DataFrame with Product records −

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

Finding sum using eval(). The resultant column with the sum is also mentioned in the eval(). The expression displays the sum formulae assigned to the resultant column −

dataFrame = dataFrame.eval('Result_Sum = Opening_Stock + Closing_Stock')

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)

# finding sum using eval()
# the resultant column with the sum is also mentioned in the eval()
# the expression displays the sum formulae assigned to the resultant column
dataFrame = dataFrame.eval('Result_Sum = Opening_Stock + Closing_Stock')
print("\nSumming rows...\n",dataFrame)

Output

This will produce the following output −

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

Summing rows...
      Product   Opening_Stock   Closing_Stock   Result_Sum
0     SmartTV             300             200          500
1  ChromeCast             700             500         1200
2     Speaker            1200            1000         2200
3    Earphone            1500             900         2400
Updated on: 2021-10-01T12:14:59+05:30

444 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements