首页 > 解决方案 > 浮点数未转换为整数熊猫

问题描述

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

Step 1: I converted timestamp1 and timestamp2 to datetime in order subtract and get days:

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

Step 2: Converted the strings into integers as the day:
df['delta'] = pd.to_datetime(df['delta'], format='%Y-%m-%d', errors='coerce')
df['delta'] = df['delta'].dt.day

Step 3: I am trying to convert floats into integers.

categorical_feature_mask = df.dtypes==object
categorical_cols = df.columns[categorical_feature_mask].tolist()

        from sklearn.preprocessing import LabelEncoder
        le = LabelEncoder()
        df[categorical_cols] = df[categorical_cols].apply(lambda col: le.fit_transform(col)) 
df[categorical_cols].head(10)


However, it throws an error TypeError: ('argument must be a string or number', 'occurred at index col1')

标签: python-3.xpandasfloating-pointinteger

解决方案


要将浮点列转换为具有 NaN 值的浮点列的整数,您可以做两件事:

  1. 转换为 naive int 并将 NaN 值更改为任意值,例如:

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

  2. 如果要保存 NaN 值,请使用:

    df[col].astype("Int32")

注意与大写“I”的区别。有关 Pandas 实现的更多信息,请查看:Nullable integer data type

为什么你需要这样做?因为默认情况下,Pandas 认为当您的列至少具有 onNaN值时,该列是 Float,因为这就是numpy的行为方式。

字符串也会发生同样的情况,如果您的列中至少有一个字符串值,则整个列将被标记object为 Pandas,所以这就是您第一次尝试失败的原因。


推荐阅读