I need to change the dtype of multiple columns (over 400) but the dataframe has different kind of dtypes. Some columns dtypes are float64 whereas some columns' are int64 or object:
print my_df.dtypes
Output:
x1                       int64
x2                       int64
x3                       object
x4                       float64
x5                       float64
x6                       float64
x7                       float64
...
x400                     object
x401                     object
x402                     object
...
I need to change all int64 to int8 or int16 and also all float64 to float32. I have tried below snippet, but it did not worked:
my_df[my_df.dtypes == np.int64].astype(np.int16)
my_df[my_df.dtypes == np.float64].astype(np.float32)
Any help is appreciated.
Thanks in advance.
Ok, I find my way :)
Find the columns that have dtype of float64
cols = my_df.select_dtypes(include=[np.float64]).columns
Then change dtype only the cols of the dataframe.
my_df[cols] = my_df[cols].astype(np.float32)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With