Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert all float64 columns to float32 in Pandas?

Is there a generic way to convert all float64 values in a pandas dataframe to float32 values? But not changing uint16 to float32? I don't know the signal names in advance but just want to have no float64.

Something like:

if float64, then convert to float32, else nothing?

The structure of the data is:

DF.dtypes

Counter               uint16
p_007                 float64
p_006                 float64
p_005                 float64
p_004                 float64
like image 664
MarK Avatar asked Dec 11 '25 23:12

MarK


2 Answers

  1. If the dataframe (say df) wholly consists of float64 dtypes, you can do:
df = df.astype('float32')
  1. Only if some columns are float64, then you'd have to select those columns and change their dtype:
# Select columns with 'float64' dtype  
float64_cols = list(df.select_dtypes(include='float64'))

# The same code again calling the columns
df[float64_cols] = df[float64_cols].astype('float32')
like image 133
Shiva Govindaswamy Avatar answered Dec 13 '25 13:12

Shiva Govindaswamy


Try this:

df[df.select_dtypes(np.float64).columns] = df.select_dtypes(np.float64).astype(np.float32)
like image 22
U12-Forward Avatar answered Dec 13 '25 13:12

U12-Forward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!