Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert type str (with number and words) column into int pandas

Tags:

python

pandas

I have a column that contains type str of both numbers and words:

ex.

['2','3','Amy','199','Happy']

And I want to convert all "str number" into int and remove (the rows with) the "str words".

So my expected output would be a list like below:

[2, 3, 199]

Since I have a pandas dataframe, and this supposed to be one of the columns, it would be even better if it could be a Series as follows:

0      2.0
1      3.0
3    199.0
dtype: float64
like image 512
GarlicSTAT Avatar asked Jan 27 '26 00:01

GarlicSTAT


1 Answers

As you mentioned you have a column (a series), so let's say it's called s:

s = pd.Series(['2', '3', 'Amy', '199', 'Happy'])

Then after assigning, just do pd.to_numeric and put the parameter of errors='coerce'. Then, remove the NaNs with dropna:

print(pd.to_numeric(s, errors='coerce').dropna())

Then the above code will output:

0      2.0
1      3.0
3    199.0
dtype: float64
like image 185
U12-Forward Avatar answered Jan 28 '26 14:01

U12-Forward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!