pandasの文字列メソッドで置換や空白削除などの処理を行う

Posted: | Tags: Python, pandas

pandas.DataFrameの列や行(= pandas.Series)の要素の文字列に対して置換などの処理を一括で行うには、pandas.Seriesの文字列メソッドを使う。str.xxx()のように文字列strアクセサで呼び出す。

例えば以下のようなメソッドがあり、Python標準の文字列(str型オブジェクト)のメソッドと同じ処理を一括で適用できる。

  • 置換
    • str.replace()
  • 空白削除
    • str.strip()
    • str.lstrip()
    • str.rstrip()
  • 大文字小文字変換
    • str.lower()
    • str.upper()
    • str.capitalize()
    • str.title()

それぞれ例を挙げて説明する。

そのほかの文字列メソッドの活用法については以下の記事を参照。

文字列を置換する

str.replace(): 文字列を置換する

import pandas as pd

s = pd.Series([' a-a-x ', ' b-x-b ', ' x-c-c '])
print(s)
# 0     a-a-x 
# 1     b-x-b 
# 2     x-c-c 
# dtype: object

s_new = s.str.replace('x', 'z')
print(s_new)
# 0     a-a-z 
# 1     b-z-b 
# 2     z-c-c 
# dtype: object

pandas.DataFrameの列を更新する(置き換える)場合は元の列に代入する。他のメソッドでも同様。

df = pd.DataFrame([[' a-a-x-1 ', ' a-a-x-2 '],
                   [' b-x-b-1 ', ' b-x-b-2 '],
                   [' x-c-c-1 ', ' x-c-c-2 ']],
                  columns=['col1', 'col2'])
print(df)
#         col1       col2
# 0   a-a-x-1    a-a-x-2 
# 1   b-x-b-1    b-x-b-2 
# 2   x-c-c-1    x-c-c-2 

df['col1'] = df['col1'].str.replace('x', 'z')
print(df)
#         col1       col2
# 0   a-a-z-1    a-a-x-2 
# 1   b-z-b-1    b-x-b-2 
# 2   z-c-c-1    x-c-c-2 

文字列の一部ではなく要素をまるごと置換したい場合は、pandas.DataFrame, pandas.Seriesreplace()メソッドを使う。以下の記事を参照。

文字列の空白を削除する

str.strip(): 左右(先頭・末尾)両方の空白を削除する

デフォルトでは左右(先頭・末尾)の空白文字が削除される。

s_new = s.str.strip()
print(s_new)
# 0    a-a-x
# 1    b-x-b
# 2    x-c-c
# dtype: object

引数に除去する文字を指定することもできる。指定した文字列に含まれる文字が除去される。str.lstrip(), str.rstrip()でも同様。

s_new = s.str.strip(' x')
print(s_new)
# 0     a-a-
# 1    b-x-b
# 2     -c-c
# dtype: object

pandas.DataFrameの場合。str.replace()と同じ。

df['col1'] = df['col1'].str.strip()
print(df)
#       col1       col2
# 0  a-a-z-1   a-a-x-2 
# 1  b-z-b-1   b-x-b-2 
# 2  z-c-c-1   x-c-c-2 

str.lstrip(): 左側(先頭)の空白を削除する

s_new = s.str.lstrip()
print(s_new)
# 0    a-a-x 
# 1    b-x-b 
# 2    x-c-c 
# dtype: object

str.rstrip(): 右側(末尾)の空白を削除する

s_new = s.str.rstrip()
print(s_new)
# 0     a-a-x
# 1     b-x-b
# 2     x-c-c
# dtype: object

大文字小文字を変換する

以下のようなpandas.Seriesを例とする。

s = pd.Series(['Hello World', 'hello world', 'HELLO WORLD'])
print(s)
# 0    Hello World
# 1    hello world
# 2    HELLO WORLD
# dtype: object

pandas.DataFrameの場合は省略する。

str.lower(): 小文字に変換する

s_new = s.str.lower()
print(s_new)
# 0    hello world
# 1    hello world
# 2    hello world
# dtype: object

str.upper(): 大文字に変換する

s_new = s.str.upper()
print(s_new)
# 0    HELLO WORLD
# 1    HELLO WORLD
# 2    HELLO WORLD
# dtype: object

str.capitalize(): 最初の文字を大文字、他を小文字に変換する

s_new = s.str.capitalize()
print(s_new)
# 0    Hello world
# 1    Hello world
# 2    Hello world
# dtype: object

str.title(): 単語の先頭の文字を大文字、他を小文字に変換する

s_new = s.str.title()
print(s_new)
# 0    Hello World
# 1    Hello World
# 2    Hello World
# dtype: object

関連カテゴリー

関連記事