Home > other >  python pandas .apply func with multiple parameters
python pandas .apply func with multiple parameters

Time:10-27

just started my first independent project in python. i want to apply my own function to a data frame. the function should take two columns of said data frame as parameters:

the function: `

def faustmann(profit, age):
    interest = 1.03
    cost = 262
    revenue = (profit - ((cost * interest) ** age)) / ((interest ** age) - 1)
    return revenue

` the data frame:


    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

applying the function:

pine_800["faustmann"] = pine_800.apply(faustmann, args=(pine_800.revenue, pine_800.age), axis=1)

with args I'm getting a

TypeError: faustmann() takes 2 positional arguments but 3 were given

with

pine_800["faustmann"] = pine_800.apply(faustmann(profit= pine_800.revenue, age=pine_800.age), axis=1)

I'm getting an: AssertionError:

with:

pine_800["faustmann"] = pine_800.apply(lambda x: faustmann(x["revenue"], x["age"]), axis=1)

I'm getting infinite (and wrong) values.

`

/tmp/ipykernel_2726/2625920579.py:8: RuntimeWarning: overflow encountered in double_scalars
  revenue = (profit - ((cost * interest) ** age)) / ((interest ** age) - 1)

`

with pine_800["faustmann"] = pine_800.apply(lambda x: (pine_800.revenue -(cost*interest**pine_800.age)/(interest*pine_800.age)-1), axis=1)

I'm getting:

ValueError: Expected a 1D array, got an array with shape (40, 40)

with:

pine_800["faustmann"] = np.vectorize(faustmann)(pine_800.revenue, age=pine_800.age)

In all cases I will get a ZeroDivisionError because profit is 0 at times. I would like to ignore it or put a NaN or div/0 string into the affected cells as excel does.

np.seterr(divide='ignore' does nothing

I'm a little lost and would appreciate all help

answers from similar problems don't seem to work for me

CodePudding user response:

can you try this:

pine_800["faustmann"] = pine_800[['revenue','age']].apply(lambda x: faustmann(x['revenue'],x['age']),axis=1)
  • Related