简体   繁体   中英

`try`/`except` block not working in pandas apply function

I am trying to apply a function to pandas dataframe. My function has a try/except block to catch exceptions like ZeroDivisionError but it's failing.

Data Frame have 100+ columns. And actual function is to be applied every row by selecting subset of columns

Following is my code

Function:

import pandas as pd
import numpy as np

def d(x):
    x0=22/7
    try:
        return x0/x
    except:
        return 0

df=pd.DataFrame({'a':[0,2,3,4],'b':[0,3,4,5]})
df

Out[174]: 
   a  b
0  0  0
1  2  3
2  3  4
3  4  5

After applying Function as

df.apply(lambda x:d(x))

Out[173]: 
          a         b
0       inf       inf
1  1.571429  1.047619
2  1.047619  0.785714
3  0.785714  0.628571

Expected 0 instead of inf at index 0

Out[173]: 
          a         b
0  0.000000  0.000000
1  1.571429  1.047619
2  1.047619  0.785714
3  0.785714  0.628571

Can anyone let me know what am I missing here. It's frustrating.... :@

Specify column:

df[0].apply(lambda x : d(x))

Out:

0    0.000000
1    3.142857
2    1.571429
3    1.047619
4    0.785714
Name: 0, dtype: float64

For entire dataset use: df.applymap(d)

Here's an alternative which will be faster than using apply if your real dataset is very large:

import math
import pandas as pd
import numpy as np

df = pd.DataFrame({'a': [0, 2, 3, 4], 'b': [0, 3, 4, 5]})
df = (math.pi / df).replace(np.inf, 0)

Results:

          a         b
0  0.000000  0.000000
1  1.570796  1.047198
2  1.047198  0.785398
3  0.785398  0.628319

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM