'How to change a string to NaN when applying astype?

I have a column in a dataframe that has integers like: [1,2,3,4,5,6..etc]

My problem: In this field one of the field has a string, like this: [1,2,3,2,3,'hello form France',1,2,3]

the Dtype of this column is object.

I want to cast it to float with column.astype(float) but I get an error because that string.

The columns has over 10.000 records and there is only this record with string. How can I cast to float and change this string to NaN for example?



Solution 1:[1]

You can use pd.to_numeric with errors='coerce'

import pandas as pd

df = pd.DataFrame({
    'all_nums':range(5),
    'mixed':[1,2,'woo',4,5],
})

df['mixed'] = pd.to_numeric(df['mixed'], errors='coerce')
df.head()

Before:

enter image description here

After:

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mitoRibo