Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore errors in pandas astype

Tags:

pandas

I have a numeric column that could contain another characters different form [0-9]. Say: x = pandas.Series(["1","1.2", "*", "1", "**."]). Then I want to convert that serie into a numerical column using x.astype(dtype = float, errors = 'ignore') . I just can't figure out why Pandas keeps giving me an error despite the fact that I ask him not to! Is there something wrong with my code ?

like image 985
Neroksi Avatar asked Jun 14 '18 13:06

Neroksi


1 Answers

I think you want to use pd.to_numeric(x, errors='coerce') instead:

In [73]: x = pd.to_numeric(x, errors='coerce')

In [74]: x
Out[74]:
0    1.0
1    1.2
2    NaN
3    1.0
4    NaN
dtype: float64

PS actually x.astype(dtype = float, errors = 'ignore') - works as expected, it doesn't give an error, it just leaves series as it is as it can't convert some elements:

In [77]: x.astype(dtype = float, errors = 'ignore')
Out[77]:
0      1
1    1.2
2      *
3      1
4    **.
dtype: object   # <----- NOTE!!!

In [81]: x.astype(dtype = float, errors = 'ignore').tolist()
Out[81]: ['1', '1.2', '*', '1', '**.']
like image 51
MaxU - stop WAR against UA Avatar answered Nov 11 '22 07:11

MaxU - stop WAR against UA