Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas change dtypes only columns of float64

Tags:

python

pandas

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.

like image 866
Ersel Er Avatar asked Aug 05 '18 22:08

Ersel Er


Video Answer


1 Answers

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)
like image 124
Ersel Er Avatar answered Oct 07 '22 09:10

Ersel Er