python-3.x - 浮点数未转换为整数熊猫
问题描述
我使用此代码将浮点数转换为整数,但是它不起作用。以下是我到目前为止所经历的所有步骤:
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')
解决方案
要将浮点列转换为具有 NaN 值的浮点列的整数,您可以做两件事:
转换为 naive int 并将 NaN 值更改为任意值,例如:
df[col].fillna(0).astype("int32")
如果要保存 NaN 值,请使用:
df[col].astype("Int32")
注意与大写“I”的区别。有关 Pandas 实现的更多信息,请查看:Nullable integer data type。
为什么你需要这样做?因为默认情况下,Pandas 认为当您的列至少具有 onNaN
值时,该列是 Float,因为这就是numpy的行为方式。
字符串也会发生同样的情况,如果您的列中至少有一个字符串值,则整个列将被标记object
为 Pandas,所以这就是您第一次尝试失败的原因。
推荐阅读
- postgresql - 为什么我在尝试登录我的 postgres 数据库时收到“致命:用户身份验证失败”?
- android - ArrayList 不能设置为模型类
- angular - 导出的动画未定义
- sql-server - 如何结合索引和列存储索引?
- html - 移动浏览器上的 Chrome v.66 自动播放
- mysql - Mysql:查找重复事件的开始
- javascript - 自动完成文本框在 asp.net 中不起作用
- json - 将 JSON 数据从 DocumentDB(或 CosmosDB)移动到 Azure Data Lake
- git - 阻止所有分支的 git force push
- ios - 在整个应用程序的 iOS 应用程序中删除后退按钮的标题或文本