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

更新日期:01-Oct-2021

404 瀏覽次數

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告