python - 如何在不获取 NaN 值的情况下将字符串列转换为数值
问题描述
我有字符串列,我必须将其转换为值。我使用了这段代码,不幸的是这个fillna
方法在这个例子中不起作用。
我该如何解决这个问题?
这是头()
data['country_txt'] = data['country_txt'].astype('float64')
data['city'] = data['city'].astype('float64')
我期望一个正常的结果,但实际输出都充满了 NaN 值:
country_txt 0 非空 float64 城市 0 非空 float64
解决方案
显然,您需要将字符串映射到integer
表示形式。
有很多不同的方法可以做到这一点。
1pd.factorize
df['country_as_int'] = pd.factorize(df['country_txt'])[0]
2LabelEncoder
from sklearn.preprocessing import LabelEncoder
f = LabelEncoder()
df['country_as_int'] = f.fit_transform(df['country_txt'])
3np.unique
df['country_as_int'] = np.unique(df['country_txt'], return_inverse=True)[-1]
推荐阅读
- gradle - 在构建结束时控制 gradle 错误日志记录
- triggers - 根据 RDS SQL Server 中的状态标志更改触发 Glue 作业
- json - 在嵌套对象上使用 @JsonUnwrapped
- domain-driven-design - 领域驱动设计存储库
- python-3.x - 在不同条件下查找字母和破折号的位置
- c# - 在 DropDownListFor 上设置选定值
- python - Tensorflow错误无法弄清楚它是什么
- arrays - 了解处理可变长度数据,特别关注 C(99) 中的可变长度数组
- mysql - 多个外键列与多个连接表
- json - Swift:如何重新加载内容拦截器