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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With