Pandas pd.to-numeric() 関数
pd.to_numeric()は Pandas ライブラリ内で使用されるデータを数値型に変換する関数です。さまざまな形式のデータ(文字列、混合型の列など)を整数や浮動小数点数などの数値型に変換できます。
これはデータクリーニングでよく使われる関数です。特にファイルやデータベースからインポートしたデータを処理する際に、数値のように見えて実際には文字列である列を変換する必要がよくあります。
単語の意味: to_numeric「数値に変換する」という意味で、データを他の型から数値型に変換することです。
基本構文とパラメータ
pd.to_numeric()は Pandas ライブラリのトップレベル関数であり、入力を数値型に変換するために使用されます。
構文形式
pd.to_numeric(arg, errors='raise', downcast=None)
パラメータの説明
- パラメータ:
arg- 型: Series、リスト、配列、または辞書のようなオブジェクト。
- 説明: 数値型に変換するデータ。通常は Series です。
- パラメータ:
errors- 型: 文字列('raise', 'coerce', 'ignore')。
- 説明: エラー処理の方法。
'raise'(デフォルト)変換できない値に遭遇すると例外をスローします;'coerce'変換できない値を NaN に設定します;'ignore'エラーを無視して、元のデータを返します。
- パラメータ:
downcast- 型: 文字列('integer', 'signed', 'unsigned', 'float')または None。
関数の説明
- 戻り値: 数値型の Series を返します。
- 効果: 入力データの型を数値型(int64 または float64)に変換します。
例
簡単なものから複雑なものまで一連の例を通して、徹底的にpd.to_numeric()使い方をマスターしましょう。
例1:基本の使い方 - 文字列を数値に変換する
例
import pandas as pd
# 1. 数値文字列を含む Series を作成
s = pd.Series(['10', '20', '30', '40', '50'])
print("=== 元の Series(型:", s.dtype, ")===")
print(s)
# 2. pd.to_numeric() を使用して数値型に変換
result = pd.to_numeric(s)
print("\n=== pd.to_numeric() 変換後(型:", result.dtype, ")===")
print(result)
# 1. 数値文字列を含む Series を作成
s = pd.Series(['10', '20', '30', '40', '50'])
print("=== 元の Series(型:", s.dtype, ")===")
print(s)
# 2. pd.to_numeric() を使用して数値型に変換
result = pd.to_numeric(s)
print("\n=== pd.to_numeric() 変換後(型:", result.dtype, ")===")
print(result)
実行結果の予想:
=== 原始 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
コード解説:
- 元のデータは文字列型(object)のため、数値演算ができません。
pd.to_numeric()整数型(int64)に変換すると、数学演算が可能になります。
例2:数値以外の文字列を含む場合の処理
使用errorsパラメータを使用すると、変換できない値を柔軟に処理できます。
例
import pandas as pd
import numpy as np
# 1. 数値以外の文字列を含む Series を作成
s = pd.Series(['10', '20', 'abc', '40', 'サンプル'])
print("=== 数値以外を含む Series ===")
print(s)
# 2. errors='raise'(デフォルト)- 変換できない値に遭遇した場合は例外をスロー
print("\n=== errors='raise'(デフォルト)===)
try:
result = pd.to_numeric(s, errors='raise')
except Exception as e:
print(f"例外: {e}")
# 3. errors='coerce' - 変換できない値を NaN に設定
print("\n=== errors='coerce' ===")
result_coerce = pd.to_numeric(s, errors='coerce')
print(result_coerce)
# 4. errors='ignore' - エラーを無視し、元のデータを返す
print("\n=== errors='ignore' ===")
result_ignore = pd.to_numeric(s, errors='ignore')
print(result_ignore)
print(f"型: {result_ignore.dtype}")
import numpy as np
# 1. 数値以外の文字列を含む Series を作成
s = pd.Series(['10', '20', 'abc', '40', 'サンプル'])
print("=== 数値以外を含む Series ===")
print(s)
# 2. errors='raise'(デフォルト)- 変換できない値に遭遇した場合は例外をスロー
print("\n=== errors='raise'(デフォルト)===)
try:
result = pd.to_numeric(s, errors='raise')
except Exception as e:
print(f"例外: {e}")
# 3. errors='coerce' - 変換できない値を NaN に設定
print("\n=== errors='coerce' ===")
result_coerce = pd.to_numeric(s, errors='coerce')
print(result_coerce)
# 4. errors='ignore' - エラーを無視し、元のデータを返す
print("\n=== errors='ignore' ===")
result_ignore = pd.to_numeric(s, errors='ignore')
print(result_ignore)
print(f"型: {result_ignore.dtype}")
実行結果の予想:
=== 包含非数值的 Series === 0 10 1 20 2 abc 3 40 4 サンプル 包含了 'abc', 'サンプル' 等无法转换的字符串 === 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 サンプル タイプ: object
コード解説:
errors='coerce'非常に実用的で、変換できない値を NaN(欠損値)に置き換え、変換できる値を保持します。errors='ignore'元のデータをそのまま維持するため、変換を試みたいがデータを変更したくない場合に適しています。
例3:数値と欠損値が混在する場合の処理
実際のデータでは、欠損値と数値が混在する列を処理する必要がよくあります。
例
import pandas as pd
import numpy as np
# 1. 欠損値と数値文字列を含む Series を作成
s = pd.Series(['100', '200', None, 'N/A', '400', '', '500'])
print("=== 欠損値と数値以外を含む Series ===")
print(s)
# 2. errors='coerce' を使用して変換
print("\n=== errors='coerce' を使用して変換 ===")
result = pd.to_numeric(s, errors='coerce')
print(result)
# 3. どの値が NaN に変換されたかを確認
print("\n=== NaN 値を識別 ===")
print(f"NaN 位置: {result.isna().tolist()}")
# 4. NaN を 0 で埋めるか削除
print("\n=== NaN を 0 で埋める ===)
print(result.fillna(0))
import numpy as np
# 1. 欠損値と数値文字列を含む Series を作成
s = pd.Series(['100', '200', None, 'N/A', '400', '', '500'])
print("=== 欠損値と数値以外を含む Series ===")
print(s)
# 2. errors='coerce' を使用して変換
print("\n=== errors='coerce' を使用して変換 ===")
result = pd.to_numeric(s, errors='coerce')
print(result)
# 3. どの値が NaN に変換されたかを確認
print("\n=== NaN 値を識別 ===")
print(f"NaN 位置: {result.isna().tolist()}")
# 4. NaN を 0 で埋めるか削除
print("\n=== NaN を 0 で埋める ===)
print(result.fillna(0))
実行結果の予想:
=== 包含缺失值和数值字符串的 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
コード解説:
errors='coerce'None、空文字列、N/A など、欠損値を表すさまざまな形式を処理し、それらをまとめて NaN に変換できます。- 変換後の型は float64 になります(NaN を表す必要があるため)。
例4:downcast パラメータを使用してメモリを最適化する
大規模なデータセットの場合、downcastパラメータを使用してメモリ使用量を削減できます。
例
import pandas as pd
import numpy as np
# 1. 大きな整数の Series を作成
s = pd.Series([1, 2, 3, 4, 5] * 100000)
print("=== 元の型:", s.dtype)
print("=== 元のメモリ:", s.memory_usage(deep=True), "bytes")
# 2. downcast を指定せずに数値に変換
result_default = pd.to_numeric(s)
print("\n=== デフォルト変換後の型:", result_default.dtype)
print("=== デフォルトのメモリ:", result_default.memory_usage(deep=True), "bytes")
# 3. より小さい整数型にダウンキャスト
result_signed = pd.to_numeric(s, downcast='signed')
print("\n=== downcast='signed' 型:", result_signed.dtype)
print("=== downcast='signed' メモリ:", result_signed.memory_usage(deep=True), "bytes")
# 4. 浮動小数点数にダウンキャスト
float_data = pd.Series([1.5, 2.5, 3.5] * 100000)
result_float = pd.to_numeric(float_data, downcast='float')
print("\n=== downcast='float' 型:", result_float.dtype)
print("=== downcast='float' メモリ:", result_float.memory_usage(deep=True), "bytes")
import numpy as np
# 1. 大きな整数の Series を作成
s = pd.Series([1, 2, 3, 4, 5] * 100000)
print("=== 元の型:", s.dtype)
print("=== 元のメモリ:", s.memory_usage(deep=True), "bytes")
# 2. downcast を指定せずに数値に変換
result_default = pd.to_numeric(s)
print("\n=== デフォルト変換後の型:", result_default.dtype)
print("=== デフォルトのメモリ:", result_default.memory_usage(deep=True), "bytes")
# 3. より小さい整数型にダウンキャスト
result_signed = pd.to_numeric(s, downcast='signed')
print("\n=== downcast='signed' 型:", result_signed.dtype)
print("=== downcast='signed' メモリ:", result_signed.memory_usage(deep=True), "bytes")
# 4. 浮動小数点数にダウンキャスト
float_data = pd.Series([1.5, 2.5, 3.5] * 100000)
result_float = pd.to_numeric(float_data, downcast='float')
print("\n=== downcast='float' 型:", result_float.dtype)
print("=== downcast='float' メモリ:", result_float.memory_usage(deep=True), "bytes")
実行結果の予想:
=== 原始类型: int64 === 原始内存: 2800000 bytes === 默认转换后类型: int64 内存节省:2.8 MB -> 1.4 MB === downcast='signed' 类型: int8/int16/int32 内存节省约 50% === downcast='float' 类型: float32 内存节省约 50%
コード解説:
- 大規模なデータセットでは、
downcastメモリ使用量を大幅に削減できます。 downcast='signed'整数を最小の符号付き整数型に変換しようとします。downcast='float'浮動小数点数を float64 から float32 に変換します。
その他の拡張ヒント:大規模なデータを処理する場合、
pd.to_numeric()組み合わせてerrors='coerce'とdowncastパラメータを使用すると、混合データを効率的に数値型に変換し、メモリを最適化できます。
Pandas 常用関数