[Python] Replacing Values in Pandas DataFrame (replace / regex)

In data cleaning processes, situations frequently arise where you need to fix typos, standardize variations, or replace specific numbers with different values. By using the Pandas replace() method, you can perform not only exact match replacements but also flexible pattern replacements using regular expressions.

This article explains basic string replacement, advanced replacement using regular expressions, and how to handle missing values (NaN).

目次

Implementation Sample Code

We will use a stationery store inventory list to perform the following three replacement tasks:

  1. Exact Match: Correct typos (e.g., “Noteboook”).
  2. Regex Replacement: Remove the suffix (color info) from the product code to standardize the category.
  3. Missing Value Replacement: Set unknown stock counts (NaN) to 0.
import pandas as pd
import numpy as np

def replace_dataframe_values():
    """
    Pandas DataFrame内の値をreplaceメソッドで置換する関数
    """
    
    # 1. サンプルデータの作成
    # 誤字や欠損値を含む文房具データ
    inventory_data = {
        "Item_Name": ["Pencill", "Noteboook", "Eraser_S", "Eraser_L", "Ruler"],
        "Category_Code": ["Pen-01", "Note-A4", "Era-01", "Era-02", "Rul-X"],
        "Stock": [150, 80, np.nan, 45, np.nan]
    }
    
    df = pd.DataFrame(inventory_data)
    
    print("--- 元のデータセット ---")
    print(df)
    print("\n")


    # 2. 完全一致による単純な置換
    print("=== 1. 文字列の完全一致置換 ===")
    
    # "Pencill" -> "Pencil", "Noteboook" -> "Notebook" に修正
    # 辞書形式で渡すことで、複数の置換を一度に行えます
    replacements = {
        "Pencill": "Pencil",
        "Noteboook": "Notebook"
    }
    
    # Item_Name列に対して置換を実行
    # df全体のreplaceも可能ですが、列を指定すると誤爆を防げます
    df["Item_Name"] = df["Item_Name"].replace(replacements)
    
    print("--- 誤字修正後のItem_Name ---")
    print(df["Item_Name"])


    # 3. 正規表現(Regex)による置換
    print("\n=== 2. 正規表現によるパターン置換 ===")
    
    # Category_Code列で、ハイフン以降(枝番)を削除してカテゴリを統一したい
    # パターン: "-.*" (ハイフンとそれに続く任意の文字) を空文字 "" に置換
    
    # regex=True を指定することで正規表現モードになります
    df["Category_Code"] = df["Category_Code"].replace(r"-.*", "", regex=True)
    
    print("--- 統一後のCategory_Code ---")
    print(df["Category_Code"])


    # 4. 欠損値(NaN)や特定の数値の置換
    print("\n=== 3. 欠損値や数値の置換 ===")
    
    # np.nan (欠損値) を 0 に置換
    # fillna(0) と同じ効果ですが、replaceは特定の値(例: -1や999)の置換にも使えます
    df["Stock"] = df["Stock"].replace(np.nan, 0)
    
    # 結果を見やすくするため整数型に変換
    df["Stock"] = df["Stock"].astype(int)
    
    print("--- 欠損値処理後のStock ---")
    print(df["Stock"])
    
    print("\n--- 最終的なDataFrame ---")
    print(df)

if __name__ == "__main__":
    replace_dataframe_values()

Execution Results

--- 元のデータセット ---
   Item_Name Category_Code  Stock
0    Pencill        Pen-01  150.0
1  Noteboook       Note-A4   80.0
2   Eraser_S        Era-01    NaN
3   Eraser_L        Era-02   45.0
4      Ruler         Rul-X    NaN


=== 1. 文字列の完全一致置換 ===
--- 誤字修正後のItem_Name ---
0      Pencil
1    Notebook
2    Eraser_S
3    Eraser_L
4       Ruler
Name: Item_Name, dtype: object

=== 2. 正規表現によるパターン置換 ===
--- 統一後のCategory_Code ---
0     Pen
1    Note
2     Era
3     Era
4     Rul
Name: Category_Code, dtype: object

=== 3. 欠損値や数値の置換 ===
--- 欠損値処理後のStock ---
0    150
1     80
2      0
3     45
4      0
Name: Stock, dtype: int64

--- 最終的なDataFrame ---
  Item_Name Category_Code  Stock
0    Pencil           Pen    150
1  Notebook          Note     80
2  Eraser_S           Era      0
3  Eraser_L           Era     45
4     Ruler           Rul      0

Explanation: Utilizing Regex Replacement

Regex replacement using regex=True is very powerful for handling inconsistencies in data.

  • Partial Match: By using wildcards (e.g., .*ggg.*), you can target entire elements that contain a specific part of a string for replacement.
  • Removing Unwanted Characters: As shown in the sample code, you can delete characters after a specific symbol (like a hyphen) or extract only numbers.

Important Note

The replace() method does not modify the original DataFrame; it returns a new DataFrame (or Series). To reflect the changes, you must either reassign the result (e.g., df = df.replace(...)) or use the inplace=True argument.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次