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

什么时候在python中应用(pd.to_numeric)和何时astype(np.float64)?

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

什么时候在python中应用(pd.to_numeric)和何时astype(np.float64)?

如果您已经拥有数字dtypes( ,

int8|16|32|64
float64
),
boolean
你可以将其转换为使用另一种“数字” D型
pandas .astype()方法。

演示:

In [90]: df = pd.Dataframe(np.random.randint(10**5,10**7,(5,3)),columns=list('abc'), dtype=np.int64)In [91]: dfOut[91]:         a        b        c0  9059440  9590567  20769181  5861102  4566089  19473232  6636568   162770  24879913  6794572  5236903  56287794   470121  4044395  4546794In [92]: df.dtypesOut[92]:a    int64b    int64c    int64dtype: objectIn [93]: df['a'] = df['a'].astype(float)In [94]: df.dtypesOut[94]:a    float64b      int64c      int64dtype: object

它不适用于 无法* 转换为数字的

object
(字符串)dtypes : *

In [95]: df.loc[1, 'b'] = 'XXXXXX'In [96]: dfOut[96]:a        b        c0  9059440.0  9590567  20769181  5861102.0   XXXXXX  19473232  6636568.0   162770  24879913  6794572.0  5236903  56287794   470121.0  4044395  4546794In [97]: df.dtypesOut[97]:a    float64b     objectc      int64dtype: objectIn [98]: df['b'].astype(float)...skipped...ValueError: could not convert string to float: 'XXXXXX'

所以在这里我们要使用pd.to_numeric()方法:

In [99]: df['b'] = pd.to_numeric(df['b'], errors='coerce')In [100]: dfOut[100]:a          b        c0  9059440.0  9590567.0  20769181  5861102.0        NaN  19473232  6636568.0   162770.0  24879913  6794572.0  5236903.0  56287794   470121.0  4044395.0  4546794In [101]: df.dtypesOut[101]:a    float64b    float64c      int64dtype: object


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

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

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