Series.str を使用すると、シリーズの値に文字列としてアクセスし、それにいくつかのメソッドを適用できます。パンダ Series.str.contains() 関数は、パターンまたは正規表現がシリーズまたはインデックスの文字列内に含まれているかどうかをテストするために使用されます。この関数は、指定されたパターンまたは正規表現がシリーズまたはインデックスの文字列内に含まれるかどうかに基づいて、ブール値のシリーズまたはインデックスを返します。
構文: Series.str.contains(pat, case=True, flags=0, na=nan, regex=True)
パラメータ:
あまりにも: 文字シーケンスまたは正規表現。
場合 : True の場合、大文字と小文字が区別されます。
フラグ: re モジュールに渡されるフラグ。 re.無視します。
それ : 欠損値の値を埋めます。
正規表現 : True の場合、pat は正規表現であると見なされます。
戻り値 : ブール値の系列またはインデックス
例 #1: Series.str.contains () 関数を使用して、指定されたシリーズ オブジェクトの基になるデータの文字列にパターンが存在するかどうかを確認します。
Python3
# importing pandas as pd> import> pandas as pd> # importing re for regular expressions> import> re> # Creating the Series> sr>=> pd.Series([>'New_York'>,>'Lisbon'>,>'Tokyo'>,>'Paris'>,>'Munich'>])> # Creating the index> idx>=> [>'City 1'>,>'City 2'>,>'City 3'>,>'City 4'>,>'City 5'>]> # set the index> sr.index>=> idx> # Print the series> print>(sr)> |
Javaでソートされた配列リスト
>
>
出力:

次に、Series.str.contains () 関数を使用して、指定されたシリーズ オブジェクトの基礎となるデータに存在する文字列にパターンが含まれているかどうかを確認します。
Python3
# find if 'is' substring is present> result>=> sr.>str>.contains(pat>=> 'is'>)> # print the result> print>(result)> |
>
>
出力:

出力でわかるように、Series.str.contains() 関数はブール値のシリーズ オブジェクトを返しました。渡されたパターンが文字列内に存在する場合は true、それ以外の場合は False が返されます。
例2: Series.str.contains () 関数を使用して、指定されたシリーズ オブジェクトの基になるデータの文字列にパターンが存在するかどうかを確認します。正規表現を使用して文字列内のパターンを検索します。
Python3
# importing pandas as pd> import> pandas as pd> # importing re for regular expressions> import> re> # Creating the Series> sr>=> pd.Series([>'Mike'>,>'Alessa'>,>'Nick'>,>'Kim'>,>'Britney'>])> # Creating the index> idx>=> [>'Name 1'>,>'Name 2'>,>'Name 3'>,>'Name 4'>,>'Name 5'>]> # set the index> sr.index>=> idx> # Print the series> print>(sr)> |
>
>
出力:

次に、Series.str.contains () 関数を使用して、指定されたシリーズ オブジェクトの基礎となるデータに存在する文字列にパターンが含まれているかどうかを確認します。
Python3
# find if there is a substring such that it has> # the letter 'i' followed by any small alphabet.> result>=> sr.>str>.contains(pat>=> 'i[a-z]'>, regex>=> True>)> # print the result> print>(result)> |
>
>
出力:

出力でわかるように、Series.str.contains() 関数はブール値のシリーズ オブジェクトを返しました。渡されたパターンが文字列内に存在する場合は true、それ以外の場合は False が返されます。