Pandas pd.to-numeric() function
pd.to_numeric() is a function in the Pandas library used toConvert data to numeric typefunction. It can convert data in various formats (such as strings and mixed-type columns) into numeric types such as integers and floats.
This is a commonly used function in data cleaning, especially when working with data imported from files or databases, where columns that look numeric but are actually strings often need to be converted.
Word meaning: to_numeric It means "convert to numeric", i.e., convert data from other types to numeric types.
Basic syntax and parameters
pd.to_numeric() is a top-level function in the Pandas library used to convert input to numeric type.
Syntax format
pd.to_numeric(arg, errors='raise', downcast=None)
Parameter Description
- Parameters:
arg - Type: Series, list, array, or dict-like object.
- Description: the data to convert to numeric type. Usually a Series.
- Parameters:
errors - Type: str ('raise', 'coerce', 'ignore').
- Description: error handling behavior.
'raise'(default) raises an exception when a value cannot be converted;'coerce'sets unconvertible values to NaN;'ignore'ignores errors and returns the original data.
- Parameters:
downcast - Type: str ('integer', 'signed', 'unsigned', 'float') or None.
Function description
- Return Value: Returns a numeric Series.
- effect: Converts the input data type to numeric (int64 or float64).
Example
Let us thoroughly master pd.to_numeric() through a series of examples from simple to complex.
Example 1: Basic usage - converting strings to numeric values
Example
import
pandas
as
pd
1. Creating a Series containing numeric strings
s
=
pd.
Series
(
[
'10'
,
'20'
,
'30'
,
'40'
,
'50'
]
)
(
"=== Original Series (dtype:"
,
s.
dtype
,
")==="
)
(
s
)
2. Converting to numeric type with pd.to_numeric()
result
=
pd.
to_numeric
(
s
)
(
"\n=== After pd.to_numeric() conversion (dtype:"
,
result.
dtype
,
")==="
)
(
result
)
Expected output:
=== 原始 Series(类型: object )===
0 10
1 20
2 30
3 40
5 50
dtype: object
=== pd.to_numeric() 转换后(类型: int64 )===
0 10
1 20
2 30
3 40
4 50
dtype: int64
Code analysis:
- The original data is of string type (object) and cannot be used in numeric operations.
pd.to_numeric()After converting it to integer type (int64), mathematical operations are possible.
Example 2: Handling strings containing non-numeric values
Use errors The argument provides flexible handling of values that cannot be converted.
Example
import
pandas
as
pd
import
numpy
as
np
1. Creating a Series containing non-numeric strings
s
=
pd.
Series
(
[
'10'
,
'20'
,
'abc'
,
'40'
,
'runoob'
]
)
(
"=== Series containing non-numeric values ==="
)
(
s
)
2. errors='raise' (default) - raise an exception when a value cannot be converted
(
"\n=== errors='raise' (default) ==="
)
try
:
result
=
pd.
to_numeric
(
s
,
errors
=
'raise'
)
except
Exception
as
e:
(
f
"Exception: {e}"
)
3. errors='coerce' - set unconvertible values to NaN
(
"\n=== errors='coerce' ==="
)
result_coerce
=
pd.
to_numeric
(
s
,
errors
=
'coerce'
)
(
result_coerce
)
4. errors='ignore' - ignore errors and return the original data
(
"\n=== errors='ignore' ==="
)
result_ignore
=
pd.
to_numeric
(
s
,
errors
=
'ignore'
)
(
result_ignore
)
(
f
"dtype: {result_ignore.dtype}"
)
Expected output:
=== 包含非数值的 Series ===
0 10
1 20
2 abc
3 40
4 runoob
包含了 'abc', 'runoob' 等无法转换的字符串
=== errors='raise'(默认)===
异常: Unable to convert string to float explicitly
=== errors='coerce' ===
0 10.0
1 20.0
2 NaN
3 40.0
4 NaN
dtype: float64
=== errors='ignore' ===
0 10
1 20
2 abc
3 40
4 runoob
类型: object
Code analysis:
errors='coerce'It is very practical: it replaces unconvertible values with NaN (missing values) while keeping convertible values.errors='ignore'It leaves the original data unchanged, which suits cases where you only want to attempt a conversion without modifying the data.
Example 3: Handling mixed numeric values and missing values
In real data, you often need to handle columns that mix missing values and numbers.
Example
import
pandas
as
pd
import
numpy
as
np
1. Creating a Series with missing values and numeric strings
s
=
pd.
Series
(
[
'100'
,
'200'
,
None
,
'N/A'
,
'400'
,
''
,
'500'
]
)
(
"=== Series with missing and non-numeric values ==="
)
(
s
)
2. Converting with errors='coerce'
(
"\n=== Converting with errors='coerce' ==="
)
result
=
pd.
to_numeric
(
s
,
errors
=
'coerce'
)
(
result
)
3. Seeing which values were converted to NaN
(
"\n=== Identifying NaN values ==="
)
(
f
"NaN positions: {result.isna().tolist()}"
)
4. Filling NaN with 0 or dropping it
(
"\n=== Filling NaN with 0 ==="
)
(
result.
fillna
(
0
)
)
Expected output:
=== 包含缺失值和数值字符串的 Series ===
0 100
1 200
2 None
3 N/A
4 400
5 (空字符串)
6 字符串 '500'
dtype: object
=== 使用 errors='coerce' 转换 ===
0 100.0
1 200.0
даль
2 NaN
3. NaN
4 400.0
5 NaN
6 NaN
dtype: float64
Code analysis:
errors='coerce'It can handle various representations of missing values such as None, empty strings, and N/A, converting them uniformly to NaN.- The converted type becomes float64 (because NaN must be represented).
Example 4: Optimizing memory with the downcast argument
For large datasets, you can use downcast the argument to reduce memory usage.
Example
import
pandas
as
pd
import
numpy
as
np
1. Creating a Series of large integers
s
=
pd.
Series
(
[
1
,
2
,
3
,
4
,
5
]
100000
)
(
"=== Original dtype:"
,
s.
dtype
)
(
"=== Original memory:"
,
s.
memory_usage
(
deep
=
True
)
,
"bytes"
)
2. Converting to numeric without specifying downcast
result_default
=
pd.
to_numeric
(
s
)
(
"\n=== Default converted dtype:"
,
result_default.
dtype
)
(
"=== Default memory:"
,
result_default.
memory_usage
(
deep
=
True
)
,
"bytes"
)
3. Downcasting to a smaller integer type
result_signed
=
pd.
to_numeric
(
s
,
downcast
=
'signed'
)
(
"\n=== downcast='signed' dtype:"
,
result_signed.
dtype
)
(
"=== downcast='signed' memory:"
,
result_signed.
memory_usage
(
deep
=
True
)
,
"bytes"
)
4. Downcasting to float
float_data
=
pd.
Series
(
[
1.5
,
2.5
,
3.5
]
100000
)
result_float
=
pd.
to_numeric
(
float_data
,
downcast
=
'float'
)
(
"\n=== downcast='float' dtype:"
,
result_float.
dtype
)
(
"=== downcast='float' memory:"
,
result_float.
memory_usage
(
deep
=
True
)
,
"bytes"
)
Expected output:
=== 原始类型: int64
=== 原始内存: 2800000 bytes
=== 默认转换后类型: int64
内存节省:2.8 MB -> 1.4 MB
=== downcast='signed' 类型: int8/int16/int32
内存节省约 50%
=== downcast='float' 类型: float32
内存节省约 50%
Code analysis:
- For large datasets,
downcastIt can significantly reduce memory usage. downcast='signed'It tries to convert integers to the smallest signed integer type.downcast='float'It converts floats from float64 to float32.
Tip: When working with large-scale data,
pd.to_numeric()combined witherrors='coerce'anddowncastthe argument can efficiently convert mixed data to numeric types and optimize memory.
Common Pandas functions