search
Search
Unlock 100+ guides
search toc
close
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
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

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

schedule Aug 12, 2023
Last updated
local_offer
PythonPandas
Tags
expand_more
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

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 ```
Edited by 0 others
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
1
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!