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

# Randomly select rows based on a condition from a Pandas DataFrame

schedule Aug 10, 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 randomly select rows based on a specific condition, we must:

1. use `DataFrame.query(~)` method to extract rows that meet the condition

2. use `DataFrame.sample(~)` method to randomly select `n` rows

# Examples

Consider the following DataFrame:

``` df = pd.DataFrame({"A":[1,2,3,4],"B":[5,6,7,8],"C":[9,10,11,12]}, index=["a","b","c","d"])df A B C a 1 5 9b 2 6 10c 3 7 11d 4 8 12 ```

## Solution

To randomly select rows where the value for column `B` is larger than `5`:

``` df.query("B > 5").sample(n=2) A B Cb 2 6 10d 4 8 12 ```

## Explanation

To break this down, `df.query("B > 5")` returns a DataFrame with rows that satisfy the condition:

``` df.query("B > 5") A B Cb 2 6 10c 3 7 11d 4 8 12 ```

The `sample(n=2)` then randomly selects `2` rows from this DataFrame.

Edited by 0 others
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
0
thumb_down
1
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!