Pandas DataFrame を列値でフィルタリングする方法
列の値を使用して Pandas DataFrame をフィルター処理することは、Python で情報を使用して実行する際の一般的な操作です。これを実現するには、さまざまな方法やテクニックを使用できます。ここでは、列の値を通じて Pandas DataFrame をフィルタリングするさまざまな方法を示します。
この投稿では、列の値で Pandas Dataframe をフィルターするさまざまな方法を見ていきます。まず、データフレームを作成しましょう。
Python3
# importing pandas> import> pandas as pd> > # declare a dictionary> record> => {> > 'Name'> : [> 'Ankit'> ,> 'Swapnil'> ,> 'Aishwarya'> ,> > 'Priyanka'> ,> 'Shivangi'> ,> 'Shaurya'> ],> > > 'Age'> : [> 22> ,> 20> ,> 21> ,> 19> ,> 18> ,> 22> ],> > > 'Stream'> : [> 'Math'> ,> 'Commerce'> ,> 'Science'> ,> > 'Math'> ,> 'Math'> ,> 'Science'> ],> > > 'Percentage'> : [> 90> ,> 90> ,> 96> ,> 75> ,> 70> ,> 80> ] }> > # create a dataframe> dataframe> => pd.DataFrame(record,> > columns> => [> 'Name'> ,> 'Age'> ,> > 'Stream'> ,> 'Percentage'> ])> # show the Dataframe> print> (> 'Given Dataframe :
'> , dataframe)> |
出力:
「>」、「=」、「=」、「 <=」、「!=」演算子を使用して、特定の列値に基づいて Pandas Dataframe の行を選択します。
例 1: 次を使用して、「パーセンテージ」が 75 より大きい、指定されたデータフレームからすべての行を選択します。 [ ] 。
Python3
# selecting rows based on condition> rslt_df> => dataframe[dataframe[> 'Percentage'> ]>>> 70> ]> > print> (> '
Result dataframe :
'> , rslt_df)> |
出力:
例 2: 次を使用して、指定されたデータフレームから「パーセンテージ」が 70 を超えるすべての行を選択します。 場所 [ ] 。
Python3
# selecting rows based on condition> rslt_df> => dataframe.loc[dataframe[> 'Percentage'> ]>>> 70> ]> > print> (> '
Result dataframe :
'> ,> > rslt_df)> |
出力:
次を使用して、列値がリストに存在する Pandas Dataframe の行を選択します。 あなた() データフレームのメソッド。
例 1: 次を使用して、オプション リストに「Stream」が存在する特定のデータフレームからすべての行を選択します。 [ ] 。
Python3
options> => [> 'Science'> ,> 'Commerce'> ]> > # selecting rows based on condition> rslt_df> => dataframe[dataframe[> 'Stream'> ].isin(options)]> > print> (> '
Result dataframe :
'> ,> > rslt_df)> |
出力:
例 2: 次を使用して、オプション リストに「Stream」が存在する特定のデータフレームからすべての行を選択します。 場所 [ ] 。
パイソン
options> => [> 'Science'> ,> 'Commerce'> ]> > # selecting rows based on condition> rslt_df> => dataframe.loc[dataframe[> 'Stream'> ].isin(options)]> > print> (> '
Result dataframe :
'> ,> > rslt_df)> |
出力:
「&」演算子を使用して複数の列条件に基づいて Pandas Dataframe の行を選択します。
例1: 次を使用して、「Age」が 22 に等しく、「Stream」がオプション リストに存在する、指定されたデータフレームからすべての行を選択します。 [ ] 。
Python3
options> => [> 'Commerce'> ,> 'Science'> ]> > # selecting rows based on condition> rslt_df> => dataframe[(dataframe[> 'Age'> ]> => => 22> ) &> > dataframe[> 'Stream'> ].isin(options)]> > print> (> '
Result dataframe :
'> ,> > rslt_df)> |
出力:
例 2: 次を使用して、「Age」が 22 に等しく、「Stream」がオプション リストに存在する、指定されたデータフレームからすべての行を選択します。 場所 [ ] 。
Python3
options> => [> 'Commerce'> ,> 'Science'> ]> > # selecting rows based on condition> rslt_df> => dataframe.loc[(dataframe[> 'Age'> ]> => => 22> ) &> > dataframe[> 'Stream'> ].isin(options)]> > print> (> '
Result dataframe :
'> ,> > rslt_df)> |
出力: