Typecast a column in pandas dataframe

Viewed 1220

I have a column with multiple types in it. As in the code below, "col1" has 2 values that are floats but when I take the overall datatype using df['col1'].dtype, it gives the output as "O".

 df['col1'].apply(lambda i: type(i)).value_counts()
 <class 'str'>      1094380
 <class 'float'>          2

 df['col1'].dtype
 Out[6]: dtype('O')

When I try to do some string computation, it throws an error because of those "float" values. If I try to typecast the entire column, that problem still persists.

Wondering is there a way to just typecast the float values and leave the rest untouched.

1 Answers

You can convert the whole column into string to do string computation using

df['column_name'].astype('str')
Related