pandasの文字列メソッドで置換や空白削除などの処理を行う
pandasでは、pandas.DataFrame
の列や行(= pandas.Series
)の要素の文字列に対して一括で処理を行うために、pandas.Series
に文字列メソッドが準備されている。
以下のようなメソッドがあり、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
source: pandas_str_replace_strip_etc.py
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
source: pandas_str_replace_strip_etc.py
文字列の空白を削除する
str.strip(): 左右(先頭・末尾)両方の空白を削除する
s_new = s.str.strip()
print(s_new)
# 0 a-a-x
# 1 b-x-b
# 2 x-c-c
# dtype: object
source: pandas_str_replace_strip_etc.py
除去する文字を引数として指定することもできる。指定した文字列に含まれる文字が除去される。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
source: pandas_str_replace_strip_etc.py
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
source: pandas_str_replace_strip_etc.py
str.lstrip(): 左側(先頭)の空白を削除する
s_new = s.str.lstrip()
print(s_new)
# 0 a-a-x
# 1 b-x-b
# 2 x-c-c
# dtype: object
source: pandas_str_replace_strip_etc.py
str.rstrip(): 右側(末尾)の空白を削除する
s_new = s.str.rstrip()
print(s_new)
# 0 a-a-x
# 1 b-x-b
# 2 x-c-c
# dtype: object
source: pandas_str_replace_strip_etc.py
大文字小文字を変換する
以下のようなpandas.Series
を例とする。
s = pd.Series(['Hello World', 'hello world', 'HELLO WORLD'])
print(s)
# 0 Hello World
# 1 hello world
# 2 HELLO WORLD
# dtype: object
source: pandas_str_replace_strip_etc.py
pandas.DataFrame
の場合は省略するが、他のメソッドと同じ方法が使える。
str.lower(): 小文字に変換する
s_new = s.str.lower()
print(s_new)
# 0 hello world
# 1 hello world
# 2 hello world
# dtype: object
source: pandas_str_replace_strip_etc.py
str.upper(): 大文字に変換する
s_new = s.str.upper()
print(s_new)
# 0 HELLO WORLD
# 1 HELLO WORLD
# 2 HELLO WORLD
# dtype: object
source: pandas_str_replace_strip_etc.py
str.capitalize(): 最初の文字を大文字、他を小文字に変換する
s_new = s.str.capitalize()
print(s_new)
# 0 Hello world
# 1 Hello world
# 2 Hello world
# dtype: object
source: pandas_str_replace_strip_etc.py
str.title(): 単語の先頭の文字を大文字、他を小文字に変換する
s_new = s.str.title()
print(s_new)
# 0 Hello World
# 1 Hello World
# 2 Hello World
# dtype: object
source: pandas_str_replace_strip_etc.py
スポンサーリンク