Home > Mobile >  Changing datatype of multiple columns by range
Changing datatype of multiple columns by range

Time:10-30

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?

CodePudding user response:

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

CodePudding user response:

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]})
  • Related