使用 eval() 函数计算行的总和 – Python Pandas
该eval()函数还可用于计算具有指定列的行的总和。首先,让我们创建一个带有产品记录的 DataFrame -
dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"],"Opening_Stock": [300, 700, 1200, 1500],"Closing_Stock": [200, 500, 1000, 900]})
使用 求总和eval()。带有总和的结果列也在eval(). 该表达式显示分配给结果列的总和公式 -
dataFrame = dataFrame.eval('Result_Sum = Opening_Stock + Closing_Stock')
示例
以下是完整的代码 -
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)
这将产生以下输出 -
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
以上是 使用 eval() 函数计算行的总和 – Python Pandas 的全部内容, 来源链接: utcz.com/z/322677.html