我使用此代码将浮点数转换为整数,但是它不起作用。这是到目前为止我完成的所有步骤:
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')
答案 0 :(得分:0)
要将浮点列转换为具有NaN值的浮点列的整数,可以执行以下两项操作:
转换为朴素的int并将NaN值更改为这样的任意值:
df[col].fillna(0).astype("int32")
如果要保留NaN值,请使用以下方法:
df[col].astype("Int32")
请注意与大写字母“ I”的区别。有关Pandas实施此实现的更多信息,请查看以下内容:Nullable integer data type。
您为什么需要这样做?因为默认情况下,Pandas认为当您的列至少具有NaN
值时,该列就是Float,因为numpy的行为就是这样。
对于字符串,也会发生同样的事情,如果您的列中至少有一个字符串值,那么对于Pandas,整个列将被标记为object
,因此这就是您第一次尝试失败的原因。