Python 在数据框中的某些列上将 Float 转换为 Int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40855969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:05:32  来源:igfitidea点击:

Converting Float to Int on certain columns in a data frame

pythonpandas

提问by Rusty

I am trying to convert columns 0 to 4 and 6 to ints from there current float types.

我正在尝试将 0 到 4 和 6 列从当前的浮点类型转换为整数。

I tried:

我试过:

df[0:4,6].astype(int)

but of course this does not work...

但这当然行不通......

回答by piRSquared

consider df

考虑 df

df = pd.DataFrame(np.random.rand(10, 10) * 10)

enter image description here

在此处输入图片说明

use np.r_to get slc

np.r_得到slc

slc = np.r_[0:4, 6]
df[slc] = df[slc].astype(int)
df

or pass a dictionary of types with keys as column names

或传递带有键作为列名的类型字典

df.astype({c: int for c in slc})

enter image description here

在此处输入图片说明