Home > other >  How to change a string to NaN when applying astype?
How to change a string to NaN when applying astype?

Time:05-19

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?

CodePudding user response:

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

  • Related