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

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐