How to convert all float64 columns to float32 in Pandas?
Question:
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
Answers:
Try this:
df[df.select_dtypes(np.float64).columns] = df.select_dtypes(np.float64).astype(np.float32)
- If the dataframe (say
df
) wholly consists of float64
dtypes, you can do:
df = df.astype('float32')
- 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')
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
Try this:
df[df.select_dtypes(np.float64).columns] = df.select_dtypes(np.float64).astype(np.float32)
- If the dataframe (say
df
) wholly consists offloat64
dtypes, you can do:
df = df.astype('float32')
- 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')