環境
- 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.