python使用pd.to_numeric()方法将数据转为数字类型int或float

pandas.to_numeric(arg, errors=‘raise’, downcast=None) [source]

将参数转换为数字类型。

默认返回dtype为float64或int64, 具体取决于提供的数据。使用downcast参数获取其他dtype。
————————————————

案例1

>>> s = pd.Series(['1.0', '2', -3])
>>> pd.to_numeric(s) # s的类型可以是 标量、元组、列表、一维数组和列表
0    1.0
1    2.0
2   -3.0
dtype: float64

>>> pd.to_numeric(s, downcast='float')
0    1.0
1    2.0
2   -3.0
dtype: float32

>>> pd.to_numeric(s, downcast='signed')
0    1
1    2
2   -3
dtype: int8

>>> s = pd.Series(['apple', '1.0', '2', -3])
>>> pd.to_numeric(s, errors='ignore') #'ignore'表示不能转的将保证原样
0    apple
1      1.0
2        2
3       -3
dtype: object

>>> pd.to_numeric(s, errors='coerce') #‘coerce'表示不能转的将被置为Nan
0    NaN
1    1.0
2    2.0
3   -3.0
dtype: float64

案例2. 支持整型和浮点型进行下放

>>> s = pd.Series([1, 2, 3], dtype="Int64")
>>> pd.to_numeric(s, downcast="integer") # int64 变为 int8
0    1
1    2
2    3
dtype: Int8

>>> s = pd.Series([1.0, 2.1, 3.0], dtype="Float64")
>>> pd.to_numeric(s, downcast="float")
0    1.0
1    2.1
2    3.0
dtype: Float32

案例3 一次性转换多列的格式

方法1

In [273]: cols = df.columns.drop('id')

In [274]: df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')

方法2

import pandas as pd  

# sample dataframe  
df = pd.DataFrame({'A': [1, 2, 3, 4, 5],
                   'B': ['a', 'b', 'c', 'd', 'e'],
                   'C': [1.1, '1.0', '1.3', 2, 5] })  

# using dictionary to convert specific columns  
convert_dict = {'A': int,
                'C': float }  

df = df.astype(convert_dict)  
print(df.dtypes)

如果要选择所有string(object)列,请使用以下简单技巧:

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

参考链接:
[1] 官方链接
[2] python numeric_Python pandas.to_numeric函数方法的使用 2021.2
[3] 关于python:pandas:多列的to_numeric 2019.9

  • 5
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值