Home » Pandas: How to Select Rows Based on Column Values

Pandas: How to Select Rows Based on Column Values

by Erma Khan

You can use one of the following methods to select rows in a pandas DataFrame based on column values:

Method 1: Select Rows where Column is Equal to Specific Value

df.loc[df['col1'] == value]

Method 2: Select Rows where Column Value is in List of Values

df.loc[df['col1'].isin([value1, value2, value3, ...])]

Method 3: Select Rows Based on Multiple Column Conditions

df.loc[(df['col1'] == value) & (df['col2']  value)]

The following example shows how to use each method with the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'],
                   'points': [5, 7, 7, 9, 12, 9, 9, 4],
                   'rebounds': [11, 8, 10, 6, 6, 5, 9, 12],
                   'blocks': [4, 7, 7, 6, 5, 8, 9, 10]})

#view DataFrame
df

	team	points	rebounds blocks
0	A	5	11	 4
1	A	7	8	 7
2	B	7	10	 7
3	B	9	6	 6
4	B	12	6	 5
5	C	9	5	 8
6	C	9	9	 9
7	C	4	12	 10

Method 1: Select Rows where Column is Equal to Specific Value

The following code shows how to select every row in the DataFrame where the ‘points’ column is equal to 7:

#select rows where 'points' column is equal to 7
df.loc[df['points'] == 7]

	team	points	rebounds blocks
1	A	7	8	 7
2	B	7	10	 7

Method 2: Select Rows where Column Value is in List of Values

The following code shows how to select every row in the DataFrame where the ‘points’ column is equal to 7, 9, or 12:

#select rows where 'points' column is equal to 7
df.loc[df['points'].isin([7, 9, 12])]

        team	points	rebounds blocks
1	A	7	8	 7
2	B	7	10	 7
3	B	9	6	 6
4	B	12	6	 5
5	C	9	5	 8
6	C	9	9	 9

Method 3: Select Rows Based on Multiple Column Conditions

The following code shows how to select every row in the DataFrame where the ‘team’ column is equal to ‘B’ and where the ‘points’ column is greater than 8:

#select rows where 'team' is equal to 'B' and points is greater than 8
df.loc[(df['team'] == 'B') & (df['points'] > 8)]

	team	points	rebounds blocks
3	B	9	6	 6
4	B	12	6	 5

Notice that only the two rows where the team is equal to ‘B’ and the ‘points’ is greater than 8 are returned.

Additional Resources

The following tutorials explain how to perform other common operations in pandas:

How to Select Rows by Index in Pandas
How to Select Unique Rows in Pandas
How to Select Rows Where Value Appears in Any Column in Pandas

Related Posts