Assume this is my df
and dtypes are int64
at the beginning.
A B C
0 1 2 3
1 5 6 7
2 8 9 10
3 13 14 15
Then I tried to convert all the values to astype str
using
df = df.astype(str)
df.dtypes
A int64
B int64
C int64
dtype: object
Now it changed the dtypes to object
like I expected. Now I tried to convert few columns to dtype int64
again using pd.to_numeric
with apply
function
df.iloc[:, 0:2] = df.iloc[:, 0:2].apply(pd.to_numeric, errors='coerce')
print(df.dtypes)
A object
B object
C object
dtype: object
This above code was executed but it didn't change the dtypes of col A and B
to int64
. They are still dtype object
. I can't understand why it didn't work.
I even tried the same code with loc
rather than iloc
but it still doesn't work the dtypes are still object
df.loc[:, ['A','B']] = df.loc[:, ['A','B']].apply(pd.to_numeric, errors='coerce')
But when I use only df[[cols]]
it works.
df[['A','B']] = df[['A','B']].apply(pd.to_numeric, errors='coerce') # This works
Note : I have searched but couldn't find anything related to my question. If this is a duplicate question please point me towards it.