python - Concise/elegant integration using pandas Series elements as bounds -


i have pandas dataframe, i'll call df. has columns 'a' , 'b'.

      b 1   0   3 2   1   4 3   2   5 

i want add column, 'c'. 'c' should definite integral of function f on bounds ('a', 'b'). @ moment, function f f(x) = x, in future have different functions that'll need mapping in, rather trivially solving integral , calculating 'c' (b^2 - a^2)/2, i'd implement programmatic solution.

the following works:

from scipy.integrate import quad  df['c'] = df.apply(lambda x: quad(lambda x: x, x[0], x[1])[0], axis=1) 

however, seems inelegant. find hard believe dataframe method applying lambda function contains function takes third function (also, moment, lambda) input really best way this.

is there less syntactically terrible way achieve end goal of defining 'c' integral of f on bounds ('a', 'b')?

i believe approach fine, recommend following improve readability:

# explicitly define function. def func(x):     # example, y = x^2     return x ** 2  # explicitly reference , b end points. df['c'] = df.apply(lambda x: quad(func, x.a, x.b)[0], axis=1) 

you can use list comprehension:

df['c'] = [quad(func, a, b)[0] a, b in zip(df.a, df.b)] 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -