- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Evaluate the sum of rows using the eval() function – 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
Advertisements