Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert all float columns in dataframe but except the first column?

Tags:

python-3.x

I have searched but not found excatly what I need. I have a dataframe which has 50 columns. The first one is a date dtype, the rest are floats dtypes.

Now I want to convert ONLY the float columns into integer but NOT the date column. Can someone guide please?

When I slice the df like this df_sub1=df_sub.iloc[:, 1:].apply(np.int64) and then concat with the date column after, it crashes my laptop and did therefore not work. I hope there is a better way.

like image 348
LaLaTi Avatar asked Sep 05 '25 03:09

LaLaTi


1 Answers

Well assuming that date is your first column

import pandas as pd

cols = df.columns
df[cols[1:]] = df[cols[1:]].apply(pd.to_numeric, errors='coerce')

like image 51
aunsid Avatar answered Sep 08 '25 00:09

aunsid