Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Changing datatype of multiple columns by range

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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]})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading