close

How to apply a function on every row on a dataframe?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to apply a function on every row on a dataframe in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to apply a function on every row on a dataframe?

  1. How to apply a function on every row on a dataframe?

    If all you're doing is calculating the square root of some result then use the np.sqrt method this is vectorised and will be significantly faster:

  2. apply a function on every row on a dataframe

    If all you're doing is calculating the square root of some result then use the np.sqrt method this is vectorised and will be significantly faster:

Method 1

The following should work:

def EOQ(D,p,ck,ch):
    Q = math.sqrt((2*D*ck)/(ch*p))
    return Q
ch=0.2
ck=5
df['Q'] = df.apply(lambda row: EOQ(row['D'], row['p'], ck, ch), axis=1)
df

If all you’re doing is calculating the square root of some result then use the np.sqrt method this is vectorised and will be significantly faster:

In [80]:
df['Q'] = np.sqrt((2*df['D']*ck)/(ch*df['p']))

df
Out[80]:
    D   p          Q
0  10  20   5.000000
1  20  30   5.773503
2  30  10  12.247449

Timings

For a 30k row df:

In [92]:

import math
ch=0.2
ck=5
def EOQ(D,p,ck,ch):
    Q = math.sqrt((2*D*ck)/(ch*p))
    return Q

%timeit np.sqrt((2*df['D']*ck)/(ch*df['p']))
%timeit df.apply(lambda row: EOQ(row['D'], row['p'], ck, ch), axis=1)
1000 loops, best of 3: 622 µs per loop
1 loops, best of 3: 1.19 s per loop

You can see that the np method is ~1900 X faster

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read