剛開始我在 python 中的第一個獨立專案。我想將我自己的函式應用于資料框。該函式應將所述資料框的兩列作為引數:
函式:`
def faustmann(profit, age):
interest = 1.03
cost = 262
revenue = (profit - ((cost * interest) ** age)) / ((interest ** age) - 1)
return revenue
` 資料框:
Year age Total_MCuFt Loblolly_MCuFt Total_SCuFt Loblolly_SCuFt pulp revenue
0 2026 0 0.0 0.0 0.0 0.0 0.0 0.000
1 2031 5 0.0 0.0 0.0 0.0 0.0 0.000
2 2036 10 214.1 214.1 0.0 0.0 214.1 57.807
3 2041 15 1908.8 1908.8 0.0 0.0 1908.8 515.376
4 2046 20 3418.4 3418.4 0.0 0.0 3418.4 922.968
應用功能:
pine_800["faustmann"] = pine_800.apply(faustmann, args=(pine_800.revenue, pine_800.age), axis=1)
使用 args 我得到一個
TypeError: faustmann() takes 2 positional arguments but 3 were given
和
pine_800["faustmann"] = pine_800.apply(faustmann(profit= pine_800.revenue, age=pine_800.age), axis=1)
我得到一個: AssertionError:
和:
pine_800["faustmann"] = pine_800.apply(lambda x: faustmann(x["revenue"], x["age"]), axis=1)
我得到了無限(和錯誤)的價值。
`
/tmp/ipykernel_2726/2625920579.py:8: RuntimeWarning: overflow encountered in double_scalars
revenue = (profit - ((cost * interest) ** age)) / ((interest ** age) - 1)
`
和
pine_800["faustmann"] = pine_800.apply(lambda x: (pine_800.revenue -(cost*interest**pine_800.age)/(interest*pine_800.age)-1), axis=1)
我越來越:
ValueError: Expected a 1D array, got an array with shape (40, 40)
和:
pine_800["faustmann"] = np.vectorize(faustmann)(pine_800.revenue, age=pine_800.age)
在所有情況下,我都會得到 ZeroDivisionError,因為利潤有時為 0。我想忽略它,或者像 excel 一樣將 NaN 或 div/0 字串放入受影響的單元格中。
np.seterr(divide='ignore'
什么也沒做
我有點迷茫,希望得到所有幫助
類似問題的答案似乎對我不起作用
uj5u.com熱心網友回復:
你能試試這個:
pine_800["faustmann"] = pine_800[['revenue','age']].apply(lambda x: faustmann(x['revenue'],x['age']),axis=1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/521411.html
