nomnom3214
nomnom3214

Reputation: 259

How to convert string to null or Nan in python?

I have this table where one of the column has string and integer, and I want to convert the string to integer as 0. How can I do this in python? The column similar like this:

size
1
1
1
2
ABC

I expect it can be converted as:

size
1
1
1
2
0

Upvotes: 2

Views: 1694

Answers (2)

Erik
Erik

Reputation: 276

You can try isinstance() function?

test=["abc",1,2,3,"def"]
for x in test:
    if isinstance(x, str): print ("0")
    else: print (x)

Output:

0
1
2
3
0

Upvotes: 0

jezrael
jezrael

Reputation: 862396

Use to_numeric with errors='coerce' for missing values instead strings, replace them by Series.fillna and last convert to integers:

df['size'] = pd.to_numeric(df['size'], errors='coerce').fillna(0).astype(int)
print (df)
   size
0     1
1     1
2     1
3     2
4     0

Upvotes: 2

Related Questions