Simple method to change DataFrame column type but use a default value for errors?

Viewed 1936

Suppose I have the following column.

>>> import pandas
>>> a = pandas.Series(['0', '1', '5', '1', None, '3', 'Cat', '2'])

I would like to be able to convert all the data in the column to type int, and any element that cannot be converted should be replaced with a 0.

My current solution to this is to use to_numeric with the 'coerce' option, fill any NaN with 0, and then convert to int (since the presence of NaN made the column float instead of int).

>>> pandas.to_numeric(a, errors='coerce').fillna(0).astype(int)
0    0
1    1
2    5
3    1
4    0
5    3
6    0
7    2
dtype: int64

Is there any method that would allow me to do this in one step rather than having to go through two intermediate states? I am looking for something that would behave like the following imaginary option to astype:

>>> a.astype(int, value_on_error=0)
2 Answers
Related