浮动未转换为整数 pandas [英] Float is not converting to integer pandas

查看:60
本文介绍了浮动未转换为整数 pandas 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此代码将我的浮点数转换为整数,但是它不起作用.到目前为止,这是我经历的所有步骤:

 步骤1:我将timestamp1和timestamp2转换为datetime,以便减去并获得天数:a = pd.to_datetime(df ['timestamp1'],format ='%Y-%m-%dT%H:%M:%SZ')b = pd.to_datetime(df ['timestamp2'],format ='%Y-%m-%dT%H:%M:%SZ')df ['delta'] =(b-a).dt.days步骤2:将字符串转换为整数作为日期:df ['delta'] = pd.to_datetime(df ['delta'],format ='%Y-%m-%d',errors ='coerce')df ['delta'] = df ['delta'].dt.day步骤3:我正在尝试将浮点数转换为整数.categorical_feature_mask = df.dtypes ==对象categorical_cols = df.columns [categorical_feature_mask] .tolist()从sklearn.preprocessing导入LabelEncoderle = LabelEncoder()df [categorical_cols] = df [categorical_cols] .apply(lambda col:le.fit_transform(col))df [categorical_cols] .head(10)但是,它将引发错误TypeError :(参数必须是字符串或数字",在索引col1处发生") 

解决方案

要将浮点列转换为具有NaN值的浮点列的整数,可以执行以下两项操作:

  1. 转换为朴素的int并将NaN值更改为这样的任意值:

    df [col] .fillna(0).astype("int32")

  2. 如果要保留NaN值,请使用以下方法:

    df [col] .astype("Int32")

请注意与大写字母"I"的区别.有关Pandas实施的更多信息,请查看以下内容:可为空的整数数据类型.

您为什么需要这样做?因为默认情况下,Pandas认为当您的列至少具有 NaN 值时,该列就是Float,因为 解决方案

To convert a float column to an integer with float columns having NaN values two things you can do:

  1. Convert to naive int and change NaN values to an arbitrary value such as this:

    df[col].fillna(0).astype("int32")

  2. If you want to conserve NaN values use this:

    df[col].astype("Int32")

Note the difference with the capital "I". For further information on this implementation made by Pandas just look at this: Nullable integer data type.

Why do you need to do that ? Because by default Pandas considers that when your column has at least on NaN value, the column is a Float, because this is how numpy behaves.

The same thing happen with strings, if you have at least one string value in your column, the whole column would be labeled as object for Pandas, so this is why your first attempt failed.

这篇关于浮动未转换为整数 pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆