2

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

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.