Pandas count number of astype errors

Viewed 68

Given a Series of type object I would like to know how many elements could successfully be cast to a given type, using the .astype() function.

For example trying to cast the following series to an float32:

s = pd.Series([1.1, 'foo', 3, '4.3', np.nan, 6, 'bar'])

The expected output of the function would just be the count of errors, in this case:

2

(note: np.nan does successfully cast to float32)

What would be the easiest way to achieve this with pandas?

1 Answers

Based on the discussion in comments, you could try pd.to_numeric with errors='coerce' and then filter the nan values out

int(pd.to_numeric(s,errors='coerce').isna().mask(s.isna()).sum())
#2

With try and except:

def fun(ser):
    l=[]
    for i in ser:
        try:
            np.float32(i)
        except ValueError:
            l.append(i)
    return l

s.isin(fun(s)).sum()
#2
Related