3

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.

Goutham
  • 435
  • 3
  • 16
  • 4
    I would say it's a bug. – DYZ Sep 14 '18 at 04:00
  • I can just add that the problem is not that `iloc` and `loc` doesn't "change" the `dtype` as is implied in the question. `df[['A', 'B']] = df.iloc[:,0:2].apply(pd.to_numeric, errors='coerce')` would update the `dtype` correctly. – user3471881 Sep 14 '18 at 07:47
  • 1
    Possible duplicate of [Pandas: unable to change column data type](https://stackoverflow.com/questions/17778139/pandas-unable-to-change-column-data-type) – user96564 Sep 14 '18 at 08:57

0 Answers0