熊猫只更改 dtypes 的 float64 列

Ers*_* Er 3 python pandas

我需要更改多列(超过 400)的 dtype,但数据框具有不同类型的 dtype。一些列 dtypes 是,float64而一些列是int64or object

print my_df.dtypes
Run Code Online (Sandbox Code Playgroud)

输出:

x1                       int64
x2                       int64
x3                       object
x4                       float64
x5                       float64
x6                       float64
x7                       float64
...

x400                     object
x401                     object
x402                     object
...
Run Code Online (Sandbox Code Playgroud)

我需要全部更改int64int8orint16并且也全部更改float64float32。我试过下面的代码片段,但没有奏效:

my_df[my_df.dtypes == np.int64].astype(np.int16)
my_df[my_df.dtypes == np.float64].astype(np.float32)
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏。

提前致谢。

Roo*_*beh 7

你快明白了!

my_df.loc[:, my_df.dtypes == 'float64'] = my_df.loc[:, my_df.dtypes == 'float64'].astype('float32')
my_df.loc[:, my_df.dtypes == 'int64'] = my_df.loc[:, my_df.dtypes == 'int64'].astype('int32')
Run Code Online (Sandbox Code Playgroud)


Ers*_* Er 6

好的,我找到了我的方式:)

查找具有 dtype 的列 float64

cols = my_df.select_dtypes(include=[np.float64]).columns
Run Code Online (Sandbox Code Playgroud)

然后仅更改cols数据帧的 dtype。

my_df[cols] = my_df[cols].astype(np.float32)
Run Code Online (Sandbox Code Playgroud)

  • 您还可以将 `np.float64` 替换为 `"float64"` 以跳过导入 numpy(如果尚未导入)。 (2认同)