Changing datatype of multiple columns by range

Question:

I know I can change the data type of columns by passing the column names, for example

df = df.astype({'col1': 'object', 'col2': 'int'})

but what if I want to change multiple columns by a given range? My df contains 50+ columns so I don’t want to change them all by name. I want to set columns 17 to 41 as ints and I’ve tried a few variations, for example:

df = df.astype([17:41], 'int64')
but can’t get the syntax to work. Any ideas?

Asked By: seevans38

||

Answers:

You can access columns by index (position).
df.iloc[:,16:42] = df.iloc[:,16:42].apply(pd.to_numeric)

Answered By: Rahul Raina

You could slice a list of the column names and unpack it in a dict comprehension!

df.astype({c: "int64" for c in df.columns[17:41]})
Answered By: ti7
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.