Skip to content Skip to sidebar Skip to footer

How To Iterate Over Pandas Df With A Def Function Variable Function

i hope you can guide me here, cause i am a little lost and not really experienced in python programing. My goal: i have to calculate the 'adducts' for a given 'Compound', both rep

Solution 1:

One way is using functools.partial together with map.

Given the regularity of your function calls, I would try something like:

from funtools import partial

deffunc(x, n):
    return x*df_M[n]/df_div[n] + df_mass[n]

for i inrange(max_i): #change max_i with the integer you need
    df[df_name.loc[i]] = map(partial(func, n=i), df["exact_mass"])
    #df[df_name.loc[i]] = df["exact_mass"].map(partial(func, n=i)) should work as well

more info here https://docs.python.org/3.7/library/functools.html#functools.partial

Solution 2:

Here's a proposition define

defA(x,i):
    returnx*df_M[i]/df_div[i] + df_mass[i]

Then doing A(x,5) is the same as A5(x). Then you loop through all your stuff:

for i in range(47):
    df[df_name.loc[i]] = df['exact_mass'].map(lambda x: A(x,i))

I think there is probably a more elegant way to do this, but this should work.

Post a Comment for "How To Iterate Over Pandas Df With A Def Function Variable Function"