Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Evaluate the sum of rows using the eval() function – Python Pandas
The eval() function in Pandas can be used to evaluate arithmetic expressions and create new columns. It's particularly useful for calculating row-wise sums across specified columns using a simple string expression.
Creating a Sample DataFrame
Let us create a DataFrame with Product records ?
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)
DataFrame...
Product Opening_Stock Closing_Stock
0 SmartTV 300 200
1 ChromeCast 700 500
2 Speaker 1200 1000
3 Earphone 1500 900
Using eval() to Sum Rows
The eval() function allows you to write arithmetic expressions as strings. The resultant column with the sum is also mentioned in the eval() expression ?
import pandas as pd
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 expression displays the sum formula assigned to the resultant column
dataFrame = dataFrame.eval('Result_Sum = Opening_Stock + Closing_Stock')
print("Summing rows...\n", dataFrame)
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
Key Benefits of eval()
The eval() method offers several advantages:
- Readable syntax: Write expressions as natural mathematical formulas
- Performance: Can be faster for complex expressions on large datasets
- Dynamic evaluation: Column names are referenced directly without bracket notation
Conclusion
The Pandas eval() function provides an intuitive way to perform row-wise calculations using string expressions. It's particularly useful for creating new columns based on arithmetic operations between existing columns.
Advertisements
