文字列操作
1. 学習内容
- ❶ ベクトル化された文字列メソッド:
np.char.upper、np.char.lowerなど。 - ❷
np.char.find、np.char.countとのパターンマッチング - ❸ 文字列の結合、分割、およびパディング
- ❹ NumPyの文字列とPythonの文字列、それぞれをいつ使うべきか
2. 主要な概念
PYTHON
import numpy as np
names = np.array(['alice', 'bob', 'charlie'])
# Vectorized string operations
print(np.char.upper(names)) # ['ALICE' 'BOB' 'CHARLIE']
print(np.char.capitalize(names)) # ['Alice' 'Bob' 'Charlie']
print(np.char.title(names)) # ['Alice' 'Bob' 'Charlie']
# Pattern matching
print(np.char.find(names, 'li')) # [ 2 -1 3]
print(np.char.count(names, 'e')) # [1 0 1]
# Join and split
print(np.char.join('-', names)) # ['a-l-i-c-e' 'b-o-b' 'c-h-a-r-l-i-e']
print(np.char.split(names, 'i')) # [['al', 'ce'], ['bob'], ['charl', 'e']]
TEXT
> Output: Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
(1) ▶ サンプル:基本的な文字列操作(難易度 ⭐)
PYTHON
import numpy as np
names = np.array(['alice', 'bob', 'charlie', 'diana'])
print("Upper:", np.char.upper(names))
print("Lower:", np.char.lower(names))
print("Capitalize:", np.char.capitalize(names))
print("Title:", np.char.title(names))
print("Swapcase:", np.char.swapcase(names))
出力:
TEXT上段:['ALICE' 'BOB' 'CHARLIE' 'DIANA'] 下段:['alice' 'bob' 'charlie' 'diana'] 大文字に変換:['Alice' 'Bob' 'Charlie' 'Diana'] タイトル:['アリス' 'ボブ' 'チャーリー' 'ダイアナ'] Swapcase: ['ALICE' 'BOB' 'CHARLIE' 'DIANA']
(2) ▶ サンプル:文字列でのパターンマッチング(難易度 ⭐⭐)
PYTHON
import numpy as np
emails = np.array(['alice@work.com', 'bob@home.org', 'charlie@school.edu'])
# Find position of '@'
at_pos = np.char.find(emails, '@')
print("@ positions:", at_pos)
# Count occurrences of 'e'
e_count = np.char.count(emails, 'e')
print("'e' counts:", e_count)
# Check start/end
print("Starts with 'a':", np.char.startswith(emails, 'a'))
print("Ends with '.edu':", np.char.endswith(emails, '.edu'))
出力:
TEXT@ 位置: [5 3 7] 「e」の出現回数:[1 1 2] 「a」で始まるもの:[ True False False] 「.edu」で終わる:[False False True]
(3) ▶ サンプル:文字列の連結とパディング(難易度 ⭐⭐)
PYTHON
import numpy as np
words = np.array(['hello', 'world', 'numpy'])
# Join characters with separator
print("Join:", np.char.join('-', words))
# Pad strings to fixed width
print("Pad center:\n", np.char.center(words, 10, fillchar='='))
print("Pad left:\n", np.char.ljust(words, 10, fillchar='.'))
print("Pad right:\n", np.char.rjust(words, 10, fillchar='.'))
# Strip whitespace
messy = np.array([' alice ', ' bob ', ' charlie '])
print("Strip:", np.char.strip(messy))
出力:
TEXT参加:['h-e-l-l-o' 'w-o-r-l-d' 'n-u-m-p-y'] パッドの中心: ['==hello===' '==world====' '==numpy===='] 左側のパッド: ['hello.....' 'world.....' 'numpy.....'] 右のパッド: ['.....hello' '.....world' '.....numpy'] ストリップ:['alice' 'bob' 'charlie']
Q NumPyの文字列演算は、Pythonのループよりも高速ですか?
A はい、大規模な配列の場合、C言語レベルのベクトル化は、Pythonの文字列を反復処理するよりもはるかに高速です。しかし、単一の文字列については、Pythonのネイティブメソッドの方がシンプルです。
Q 文字列配列のデータ型は何ですか?
A
np.str_(Unicodeの場合は'U')です。文字列配列には固定の最大長があり、それによってメモリ使用量が決まります。 可変長の文字列には object データ型が使用されます。Q 正規表現は使えますか?
A NumPyには正規表現のネイティブサポートはありません。配列に対する正規表現操作を行うには、
np.vectorize(re.search) または Pandas .str.contains() を使用してください。❓ よくある質問
Q 最も重要なポイントは何か?
A NumPyの演算はベクトル化されているため、パフォーマンスを向上させるにはPythonのループは避けるべきだ。
Q さらに詳しく知りたい場合はどうすればよいですか?
A 詳細なリファレンスや高度なトピックについては、numpy.org の NumPy 公式ドキュメントをご覧ください。
Q これはNumPy 2.xでも動作しますか?
A はい。すべての例はNumPy 2.xと互換性があります。一部の古いAPI(np.random.seedなど)は引き続きサポートされていますが、最新の代替APIの使用をお勧めします。
📖 まとめ
np.charモジュールは、文字列のベクトル化処理(大文字化、小文字化、頭文字大文字化、タイトル形式)を提供します。- パターン一致:
find、count、startswith、endswith - 結合、分割、部分削除、パディング、置換 — すべてベクトル化されています
- 文字列配列のデータ型は固定幅です (
U{n}) — メモリは事前に割り当てられています - 複雑な文字列操作を行う場合は、Pandas
.strのアクセサの利用を検討してください
📝 練習問題
-
初心者(難易度 ⭐):5つの名前からなる配列を作成してください。
upper、lower、capitalize、およびtitleをすべての要素に適用してください。 -
中級(難易度 ⭐⭐):メールアドレスの配列を作成してください。
np.char.findを使用して、各メールアドレス内の「@」の位置を特定します。次に、np.char.splitを使用してドメイン部分を抽出してください。 -
上級 (難易度 ⭐⭐⭐): 1000個のランダムな文字列からなる配列を作成してください。
np.char.upperと Python のリスト内包表記を比較してベンチマークを行い、速度向上率を記録してください。