Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas pd.to-numeric() function

Pandas pd.to-numeric() function

Pandas Universal Functions Common Pandas functions


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

- Type: Series, list, array, or dict-like object. - Description: the data to convert to numeric type. Usually a Series. - 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. - Type: str ('integer', 'signed', 'unsigned', 'float') or None.

Function description


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'

]

)

print

(

"=== Original Series (dtype:"

,

s.

dtype

,

")==="

)

print

(

s

)

2. Converting to numeric type with pd.to_numeric()

result

=

pd.

to_numeric

(

s

)

print

(

"\n=== After pd.to_numeric() conversion (dtype:"

,

result.

dtype

,

")==="

)

print

(

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:

  1. The original data is of string type (object) and cannot be used in numeric operations.
  2. 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'

]

)

print

(

"=== Series containing non-numeric values ==="

)

print

(

s

)

2. errors='raise' (default) - raise an exception when a value cannot be converted

print

(

"\n=== errors='raise' (default) ==="

)

try

:

    result

=

pd.

to_numeric

(

s

,

errors

=

'raise'

)

except

Exception

as

e:

   

print

(

f

"Exception: {e}"

)

3. errors='coerce' - set unconvertible values to NaN

print

(

"\n=== errors='coerce' ==="

)

result_coerce

=

pd.

to_numeric

(

s

,

errors

=

'coerce'

)

print

(

result_coerce

)

4. errors='ignore' - ignore errors and return the original data

print

(

"\n=== errors='ignore' ==="

)

result_ignore

=

pd.

to_numeric

(

s

,

errors

=

'ignore'

)

print

(

result_ignore

)

print

(

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:

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'

]

)

print

(

"=== Series with missing and non-numeric values ==="

)

print

(

s

)

2. Converting with errors='coerce'

print

(

"\n=== Converting with errors='coerce' ==="

)

result

=

pd.

to_numeric

(

s

,

errors

=

'coerce'

)

print

(

result

)

3. Seeing which values were converted to NaN

print

(

"\n=== Identifying NaN values ==="

)

print

(

f

"NaN positions: {result.isna().tolist()}"

)

4. Filling NaN with 0 or dropping it

print

(

"\n=== Filling NaN with 0 ==="

)

print

(

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:

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

)

print

(

"=== Original dtype:"

,

s.

dtype

)

print

(

"=== Original memory:"

,

s.

memory_usage

(

deep

=

True

)

,

"bytes"

)

2. Converting to numeric without specifying downcast

result_default

=

pd.

to_numeric

(

s

)

print

(

"\n=== Default converted dtype:"

,

result_default.

dtype

)

print

(

"=== Default memory:"

,

result_default.

memory_usage

(

deep

=

True

)

,

"bytes"

)

3. Downcasting to a smaller integer type

result_signed

=

pd.

to_numeric

(

s

,

downcast

=

'signed'

)

print

(

"\n=== downcast='signed' dtype:"

,

result_signed.

dtype

)

print

(

"=== 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'

)

print

(

"\n=== downcast='float' dtype:"

,

result_float.

dtype

)

print

(

"=== 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:


Tip: When working with large-scale data,pd.to_numeric() combined with errors='coerce' and downcast the argument can efficiently convert mixed data to numeric types and optimize memory.

Pandas Common Functions Common Pandas functions