【问题标题】:How to convert all float64 columns to float32 in Pandas?如何在 Pandas 中将所有 float64 列转换为 float32?
【发布时间】:2021-09-15 06:37:31
【问题描述】:

是否有一种通用方法可以将 pandas 数据框中的所有 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

【问题讨论】:

    标签: python pandas type-conversion dtype


    【解决方案1】:

    试试这个:

    df[df.select_dtypes(np.float64).columns] = df.select_dtypes(np.float64).astype(np.float32)
    

    【讨论】:

    • 完美解决方案!谢谢
    【解决方案2】:
    1. 如果数据框(例如 df)完全由 float64 dtypes 组成,您可以这样做:
    df = df.astype('float32')
    
    1. 仅当某些列是 float64 时,您才必须选择这些列并更改它们的 dtype:
    # Select columns with 'float64' dtype  
    float64_cols = list(df.select_dtypes(include='int32'))
    
    # The same code again calling the columns
    df[float64_cols] = df[float64_cols].astype('float32')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-14
      • 2016-05-15
      • 2018-01-30
      • 1970-01-01
      • 2017-12-08
      • 2019-05-21
      • 2021-07-12
      • 1970-01-01
      相关资源
      最近更新 更多