0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

`pandas.to_numeric`: `errors="ignore"`を指定した場合、数値に変換できない要素のみ無視されるのではなく、変換が実行されない

Last updated at Posted at 2025-04-17

環境

  • Python 3.13.1
  • pandas 2.2.3

やりたいこと

pandas.Seriesには文字列型の値が格納されています。数値型に変換できる要素のみ数値型に変換したいです。

In [29]: s = pd.Series(['apple', '2'])
In [30]: s
Out[30]:
0    apple
1        2
dtype: object

ハマったこと

pandas.to_numericを使って、errors="ignore"を指定しました。

In [36]: s_ignore = pd.to_numeric(s, errors="ignore")
<ipython-input-36-10ba5326fdc0>:1: FutureWarning: errors='ignore' is deprecated and will raise in a future version. Use to_numeric without passing `errors` and catch exceptions explicitly instead
  s_ignore = pd.to_numeric(s, errors="ignore")

In [41]: s_ignore
Out[41]:
0    apple
1        2
dtype: object

In [37]: for v in s_ignore:
    ...:     print(f"{v=}, {type(v)=}")
    ...:
v='apple', type(v)=<class 'str'>
v='2', type(v)=<class 'str'>

'2'は数値型に変換されることを期待しましたが、変換されませんでした。

  • If ‘raise’, then invalid parsing will raise an exception.
  • If ‘coerce’, then invalid parsing will be set as NaN.
  • If ‘ignore’, then invalid parsing will return the input.

return the input.inputは、引数に渡したpandas.Seriesそのものを指しているようです。

解決

errors="coerce"を指定して解決しました。

In [38]: s_coerce = pd.to_numeric(s, errors="coerce")

In [40]: s_coerce
Out[40]:
0    NaN
1    2.0
dtype: float64

In [39]: for v in s_coerce:
    ...:     print(f"{v=}, {type(v)=}")
    ...:
v=nan, type(v)=<class 'float'>
v=2.0, type(v)=<class 'float'>

補足

errors="ignore"はひすいs

“ignore” is deprecated. Catch exceptions explicitly instead.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?