search
Search
Map of Data Science
Guest 0reps
exit_to_appLog out
Map of data science
Thanks for the thanks!
close
account_circle
Profile
exit_to_app
Sign out
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview Doc Search Code Search Beta SORRY NOTHING FOUND!
mic
Start speaking... Voice search is only supported in Safari and Chrome.
Shrink
Navigate to
A
A
brightness_medium
share
arrow_backShare Twitter Facebook

# Getting rows from a DataFrame based on column values in Pandas

Pandas
chevron_right
Cookbooks
chevron_right
DataFrame Cookbooks
chevron_right
Selecting Data Cookbook
schedule Jul 1, 2022
Last updated
local_offer PythonPandas
Tags
expand_more
map
Check out the interactive map of data science

To get rows from a DataFrame based on column values, use the DataFrame's `query(~)` method.

Consider the following DataFrame:

``` df = pd.DataFrame({"A":[3,4,5], "B":[6,7,8]}, index=["a","b","c"])df A Ba 3 6b 4 7c 5 8 ```

# Equality

To get all rows where the value for column `A` equals `4`:

``` df.query("A == 4") A Bb 4 7 ```

For a not-equals query, use `!=` instead

Note that if the value is of type string, then wrap the value in `'` or `"` like so:

``` df = pd.DataFrame({"A":["a","b"]})df.query("A == 'a'") A0 a ```

# Inequality

To get all rows where the value for column `A` is greater than `3`:

``` df.query("A > 3") A Bb 4 7c 5 8 ```

# AND queries

To get all rows where `A > 3` and `B < 8`:

``` df.query("A > 3 & B < 8") A Bb 4 7 ```

Here, you could use `"and"` instead of `"&"` like so:

``` df.query("A > 3 and < 8") A Bb 4 7 ```

# OR queries

To get all rows where `A == 3` or `B == 8`:

``` df.query("A == 3 | B == 7") A Ba 3 6b 4 7 ```

Here, you could use `"or"` instead of `"|"` like so:

``` df.query("A == 3 or B == 7") A Ba 3 6b 4 7 ```

For your reference, we show the `df` again:

``` df A Ba 3 6b 4 7c 5 8 ```

# Queries with column-comparison

To get all rows where the value for column `B` is greater than that for column `A`:

``` df.query("A < B") A Ba 3 6b 4 7c 5 8 ```

# Queries with arithmetic operations

To get all rows where value for column `B` equals is based on some function of `A`:

``` df.query("B == (A*2)-2") A Bc 5 8 ```