Boolean Indexing method
In this method, for a specified column condition, each row is checked for true/false. The rows which yield True will be considered for the output. This can be achieved in various ways. The query used is Select rows where the column Pid=’p01′
Example 1: Select rows from a Pandas DataFrame based on values in a column
In this example, we are trying to select those rows that have the value p01 in their column using the equality operator.
Python3
# Choose entries with id p01 df_new = df[df[ 'Pid' ] = = 'p01' ] print (df_new) |
Output
Example 2: Specifying the condition ‘mask’ variable
Here, we will see Pandas select rows by condition the selected rows are assigned to a new Dataframe with the index of rows from the old Dataframe as an index in the new one and the columns remaining the same.
Python3
# condition mask mask = df[ 'Pid' ] = = 'p01' # new dataframe with selected rows df_new = pd.DataFrame(df[mask]) print (df_new) |
Output
Example 3: Combining mask and dataframes.values property
The query here is to Select the rows with game_id ‘g21’.
Python3
# condition with df.values property mask = df[ 'game_id' ].values = = 'g21' # new dataframe df_new = df[mask] print (df_new) |
Output
How to select rows from a dataframe based on column values ?
Prerequisite: Pandas.Dataframes in Python
In this article, we will cover how we select rows from a DataFrame based on column values in Python.
The rows of a Dataframe can be selected based on conditions as we do use the SQL queries. The various methods to achieve this is explained in this article with examples.