3
2

More than 3 years have passed since last update.

【pandas】Dataframeで正規表現で置換

Posted at

DataFrameで正規表現を利用して文字列置換をしたい

replaceメソッドを使えば可能でした。ドキュメントはここ

以下のサンプルコードはnameカラムの先頭の「あいう」という文字列を「aiu」に置き換えるだけのかんたんな例です。

regex_replace.py
import pandas as pd
import re

df = pd.DataFrame(
    data={
        'name': ['あいうえお', 'かきくけこ', 'サシスセソ'],
        'kind': ['ひらがな', 'ひらがな', 'カタカナ']
    }
)
df["name"] = df["name"].replace(re.compile(r"^あいう"), 'aiu', regex=True)
print(df)

結果

    name  kind
0  aiuえお  ひらがな
1  かきくけこ  ひらがな
2  サシスセソ  カタカナ
3
2
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
3
2