使用 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
广告