Python: Changing int64 to float64 by indexing multiple columns

Viewed 387

While I am finding a lot of things out there concerning changing the datatype for a single column or a few columns by name, I am having a difficult time finding anything concerning changing many columns without typing all the specific names.

I would like to change all int64 to float64 without having to manually specify all 60 columns. I have found this:

df[column_list] = df[column_list].apply(pd.to_numeric, errors='coerce')

however creating a list such as: column_list = list(df[6:]) doesn't even seem to give a list that starts at column 7.

1 Answers

Use DataFrame.iloc , first : means select all rows, second all columns strat by 7th column:

df = pd.DataFrame({
        'A':list('abcdef'),
         'B':[4,5,4,5,5,4],
         'C':[7,8,9,4,2,3],
         'D':[1,3,5,7,1,0],
         'E':['a',5,4,5,5,4],
         'F':[7,'a',9,4,2,3],
         'G':[1,3,5,7,1,0],
         'H':[4,5,'a',5,5,4],
         'I':[7,8,9,4,2,3],
         'J':[1,3,5,'a',1,0],
         'K':[5,'a',6,9,2,4]
})

print (df.dtypes)
A    object
B     int64
C     int64
D     int64
E    object
F    object
G     int64
H    object
I     int64
J    object
K    object
dtype: object

df.iloc[:, 6:] = df.iloc[:, 6:].apply(pd.to_numeric, errors='coerce', downcast='float')

print (df.dtypes)
dtype: object
A     object
B      int64
C      int64
D      int64
E     object
F     object
G    float64
H    float64
I    float64
J    float64
K    float64
dtype: object

If all values are integers:

df.iloc[:, 6:] = df.iloc[:, 6:].astype(np.float64)
Related