Pandas: 文字列の長さに基づいて行をフィルタリングする方法


次のメソッドを使用して、pandas DataFrame 内の特定の長さの文字列を含む行をフィルターできます。

方法 1: 列内の文字列の長さに基づいて行をフィルターする

 #filter rows where col1 has a string length of 5
df. loc [df[' col1 ']. str . len () == 5 ]

方法 2: 複数のの文字列長に基づいて行をフィルターする

 #filter rows where col1 has string length of 5 and col2 has string length of 7
df. loc [(df[' col1 ']. str . len () == 5 ) & (df[' col2 ']. str . len () == 7 )]

次の例は、次の pandas DataFrame で各メソッドを実際に使用する方法を示しています。

 import pandas as pd

#createDataFrame
df = pd. DataFrame ({' conf ': ['East', 'East', 'North', 'West', 'North', 'South'],
                   ' pos ': ['Guard', 'Guard', 'Forward', 'Center', 'Center', 'Forward'],
                   ' points ': [5, 7, 7, 9, 12, 9]})

#view DataFrame
print (df)

    conf pos points
0 East Guard 5
1 East Guard 7
2 North Forward 7
3 West Center 9
4 North Center 12
5 South Forward 9

例 1: 列内の文字列の長さに基づいて行をフィルターする

次のコードは、 conf列の文字列長が5である DataFrame の行をフィルターする方法を示しています。

 #filter rows where conf has a string length of 5
df. loc [df[' conf ']. str . len () == 5 ]

	conf pos points
2 North Forward 7
4 North Center 12
5 South Forward 9

conf列の文字列長が5である行のみが返されます。

conf列で 2 つの異なる文字列がこの基準を満たしていることがわかります。

  • “北”
  • “南”

どちらの文字列も長さは5です。

例 2: 複数の列の文字列長に基づいて行をフィルタリングする

次のコードは、 conf列の文字列長が5pos列の文字列長が7である DataFrame の行をフィルタリングする方法を示しています。

 #filter rows where conf has string length of 5 and pos has string length of 7
df. loc [(df[' conf ']. str . len () == 5 ) & (df[' pos ']. str . len () == 7 )]

        conf pos points
2 North Forward 7
5 South Forward 9

conf列の文字列長が5で、 pos列の強制長が7である行のみが返されます。

: pandas のstr.len()関数の完全なドキュメントは、ここで見つけることができます。

追加リソース

次のチュートリアルでは、パンダで他の一般的な操作を実行する方法を説明します。

条件に基づいて Pandas DataFrame の行を削除する方法
複数の条件で Pandas DataFrame をフィルタリングする方法
Pandas DataFrame で「NOT IN」フィルターを使用する方法

コメントを追加する

メールアドレスが公開されることはありません。 が付いている欄は必須項目です