piRSquared
piRSquared

Reputation: 294338

Convert a str typed series to numeric where I can

Consider the str type series s

s = pd.Series(['a', '1'])

pd.to_numeric(s, 'ignore')

0    a
1    1
dtype: object

pd.to_numeric(s, 'ignore').apply(type)

0    <type 'str'>
1    <type 'str'>
dtype: object

Clearly, both types are still string. It seems that the 'ignore' option ignores the entires series conversion. How do I get it to do what it can and ignore the rest.

I want the series types to be

pd.to_numeric(s, 'ignore').apply(type)

0    <type 'str'>
1    <type 'int'>
dtype: object

EDIT: I came up with this after I posted the question and after @ayhan provided an answer.

My solution
Not vectorized, but gives me exactly what I want

s.apply(pd.to_numeric, errors='ignore')

Upvotes: 1

Views: 232

Answers (1)

user2285236
user2285236

Reputation:

This is what I am using:

pd.to_numeric(s, errors='coerce').fillna(s)
Out: 
0    a
1    1
dtype: object

pd.to_numeric(s, errors='coerce').fillna(s).apply(type)
Out: 
0      <class 'str'>
1    <class 'float'>
dtype: object

Upvotes: 3

Related Questions