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

# Removing rows at random without shuffling in Pandas DataFrame

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!

# Solution

To remove rows at random without shuffling in Pandas DataFrame:

1. Get an array of randomly selected row index labels.

2. Use the `drop(~)` method to remove the rows.

# Example

As an example, consider the following DataFrame:

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

To randomly remove `2` rows from `df` without shuffling:

``` from numpy.random import default_rngarr_indices_top_drop = default_rng().choice(df.index, size=2, replace=False)df.drop(index=arr_indices_top_drop) A Ba 2 6c 4 8 ```

Note that `drop(~)` creates and returns a new DataFrame, and so the original `df` is kept intact. To directly modify `df`, set `inplace=True`.

## Explanation

We first get two row labels at random like so:

``` arr_indices_top_drop = default_rng().choice(df.index, size=2, replace=False)arr_indices_top_drop array(['d', 'b'], dtype=object) ```

Here, `replace=False` means that we want to randomly select unique values without repetition. We then pass this array directly into the `drop(~)` method to remove the rows.

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