パンダ: ブール値系列を使用して dataframe から行を選択します


次の基本構文を使用して、ブール系列の値に基づいて pandas DataFrame 内の行を選択できます。

 #define boolean series
bools = pd. Series ([ True , False , True , True , False , False , False , True ])

#select rows in DataFrame based on values in boolean series
df[bools. values ]

これにより、ブール系列の対応する値がTrueであるパンダ データフレーム内の各行を選択できます。

次の例は、この構文を実際に使用する方法を示しています。

例: ブール値シリーズを使用した Pandas DataFrame の行の選択

さまざまなバスケットボール選手に関する情報を含む次のパンダ データフレームがあるとします。

 import pandas as pd

#createDataFrame
df = pd. DataFrame ({' team ': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
                   ' points ': [18, 22, 19, 14, 14, 11, 20, 28],
                   ' assists ': [5, 7, 7, 9, 12, 9, 9, 4],
                   ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12]})

#view DataFrame
print (df)

  team points assists rebounds
0 A 18 5 11
1 B 22 7 8
2 C 19 7 10
3 D 14 9 6
4 E 14 12 6
5 F 11 9 5
6 G 20 9 9
7:28 4 12

次の構文を使用して、ブール系列の対応する値がTrueである DataFrame 内のすべての行を選択できます。

 #define boolean series
bools = pd. Series ([ True , False , True , True , False , False , False , True ])

#select rows in DataFrame based on values in boolean series
df[bools. values ]

     team points assists rebounds
0 A 18 5 11
2 C 19 7 10
3 D 14 9 6
7:28 4 12

返される行は、ブール系列の対応する値がTrueである行のみであることに注意してください。

また、次の構文を使用すると、Boolean シリーズの対応する値がTrueである DataFrame の “points” 列の行のみを選択できることにも注意してください。

 #define boolean series
bools = pd. Series ([ True , False , True , True , False , False , False , True ])

#select rows in points column based on values in boolean series
df[' points '][bools. values ]

0 18
2 19
3 14
7 28
Name: points, dtype: int64

「points」列によって返される行は、ブール系列の対応する値がTrueである行のみであることに注意してください。

追加リソース

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

Pandas で文字列の長さに基づいて行をフィルターする方法
PandasでNaN値のない行を選択する方法
Pandasで列の値に基づいて行を選択する方法

コメントを追加する

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