如何在Pandas中将所有float64列转换为float32?

12

是否有一种通用的方法可以将 pandas dataframe 中所有 float64 值转换为 float32 值?但不更改 uint16 为 float32?我不知道信号名称,只是想没有 float64。

类似于:

if float64, then convert to float32, else nothing?

数据的结构为:
DF.dtypes

Counter               uint16
p_007                 float64
p_006                 float64
p_005                 float64
p_004                 float64
2个回答

17
  1. 如果数据框(比如说df)全部由float64类型组成,你可以执行以下操作:
df = df.astype('float32')
  1. 只有当某些列的类型是float64时,你才需要选择这些列并更改它们的数据类型:
# 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')

12
请尝试以下方法:
df[df.select_dtypes(np.float64).columns] = df.select_dtypes(np.float64).astype(np.float32)

1
完美的解决方案!谢谢。 - MarK

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接