栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

大熊猫:to_numeric用于多列

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

大熊猫:to_numeric用于多列

更新: 您以后不需要转换值,可以在读取CSV时 即时 进行:

In [165]: df=pd.read_csv(url, index_col=0, na_values=['(NA)']).fillna(0)In [166]: df.dtypesOut[166]:Geoname         objectComponentName   objectIndustryId       int64IndustryClassification     objectDescription     object2004  int642005  int642006  int642007  int642008  int642009  int642010  int642011  int642012  int642013  int642014float64dtype: object

如果您需要将多列转换为数字dtypes,请使用以下技术:

样本来源DF:

In [271]: dfOut[271]:     id    a  b  c  d  e    f0  id_3  AAA  6  3  5  8    11  id_9    3  7  5  7  3  BBB2  id_7    4  2  3  5  4    23  id_0    7  3  5  7  9    44  id_0    2  4  6  4  0    2In [272]: df.dtypesOut[272]:id    objecta     objectb      int64c      int64d      int64e      int64f     objectdtype: object

将选定的列转换为数字dtypes:

In [273]: cols = df.columns.drop('id')In [274]: df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')In [275]: dfOut[275]:     id    a  b  c  d  e    f0  id_3  NaN  6  3  5  8  1.01  id_9  3.0  7  5  7  3  NaN2  id_7  4.0  2  3  5  4  2.03  id_0  7.0  3  5  7  9  4.04  id_0  2.0  4  6  4  0  2.0In [276]: df.dtypesOut[276]:id     objecta     float64b       int64c       int64d       int64e       int64f     float64dtype: object

PS,如果要选择 所有

string
object
)列,请使用以下简单技巧:

cols = df.columns[df.dtypes.eq('object')]


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/637678.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号