You can group the data by target and then sample,

df = pd.DataFrame({'col':np.random.randn(12000), 'target':np.random.randint(low = 0, high = 2, size=12000)})
new_df = df.groupby('target').apply(lambda x: x.sample(n=5000)).reset_index(drop = True)

new_df.target.value_counts()

1    5000
0    5000

Edit: Use DataFrame.sample

You get similar results using DataFrame.sample

new_df = df.groupby('target').sample(n=5000)
Answer from Vaishali on Stack Overflow
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.sample.html
pandas.DataFrame.sample — pandas 3.0.5 documentation
>>> df.sample(frac=2, replace=True, random_state=1) num_legs num_wings num_specimen_seen dog 4 0 2 fish 0 0 8 falcon 2 2 10 falcon 2 2 10 fish 0 0 8 dog 4 0 2 fish 0 0 8 dog 4 0 2 · Using a DataFrame column as weights. Rows with larger value in the num_specimen_seen column are more likely to be sampled.
Discussions

python - Random sampling pandas based on column values - Stack Overflow
I have files (A,B,C etc) each having 12,000 data points. I have divided the files into batches of 1000 points and computed the value for each batch. So now for each file we have 12 values, which is More on stackoverflow.com
🌐 stackoverflow.com
September 4, 2017
python - Sample Pandas dataframe based on multiple values in column - Stack Overflow
I'm trying to even up a dataset for machine learning. There are great answers for how to sample a dataframe with two values in a column (a binary choice). In my case I have many values in column x. I More on stackoverflow.com
🌐 stackoverflow.com
python - Sample pandas dataframe by column value - Stack Overflow
I have a pandas dataframe, named ratings_full, of the form: userID nr_votes 123 12 124 14 234 22 346 35 763 45 238 1 127 17 I want to sample this dataframe, as... More on stackoverflow.com
🌐 stackoverflow.com
May 26, 2020
python - pandas sample based on criteria - Stack Overflow
But your latter approach would ... 100 values? 2017-11-22T10:44:22.243Z+00:00 ... @destinychoice Updated. If I did help, if you could mark as solution / upvote, it'd help a lot. 2017-11-22T10:46:37.373Z+00:00 ... @Neil how can I add multiple criteria? for example if I wanted to sample based on col a=1, ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Note.nkmk.me
note.nkmk.me › home › python › pandas
pandas: Random sampling from DataFrame with sample() | note.nkmk.me
May 22, 2022 - The number of rows or columns to be selected can be specified in the n parameter. print(df.sample(n=3)) # sepal_length sepal_width petal_length petal_width species # 29 4.7 3.2 1.6 0.2 setosa # 67 5.8 2.7 4.1 1.0 versicolor # 18 5.7 3.8 1.7 0.3 setosa
🌐
SoftHints
blog.softhints.com › pandas-random-sample-of-a-subset-of-a-dataframe-rows-or-columns
Pandas - Random Sample of a subset of a DataFrame - rows or columns - Softhints
February 10, 2022 - Lets work again with the same column color and this time to sample rows all except - 'Color' - in this case we can use np.where in order to built weights. This weights will be passed to method sample which is going to generate samples based on our weighted list: # excluding 'Color' values by applying weights 0 - Color and 1 - rest df['weights'] = np.where(df['color'] == 'Color', .0, 1) df.sample(frac=.001, weights='weights')
🌐
Scaler
scaler.com › home › topics › what is pandas dataframe sample() method?
What is Pandas DataFrame sample() Method? - Scaler Topics
May 4, 2023 - Finally, let's try to give more importance to a specific column using the weights parameter for the pandas sample() method to extract the necessary number or proportion of rows based on the values in that column.
Top answer
1 of 2
5

If I understand what you are trying to get at, the following should be of help:

# Test dataframe
import numpy as np
import pandas as pd


data = pd.DataFrame({'file': np.repeat(['A', 'B', 'C'], 12),
                     'value_1': np.repeat([1,0,1],12),
                     'value_2': np.random.randint(20, 100, 36)})
# Select a file
data1 = data[data.file == np.random.choice(data['file'].unique())].reset_index(drop=True)

# Get a random index from data1
start_ix = np.random.choice(data1.index[:-3])

# Get a sequence starting at the random index from the previous step
print(data.loc[start_ix:start_ix+3])
2 of 2
3

Here's a rather long winded answer that has a lot of flexibility and uses some random data I generated. I also added a field to the dataframe to denote whether that row had been used.

Generating Data

import pandas as pd
from string import ascii_lowercase
import random

random.seed(44)

files = [ascii_lowercase[i] for i in range(4)]
value_1 = random.sample(range(1, 10), 8)

files_df = files*len(value_1)
value_1_df = value_1*len(files)
value_1_df.sort()
value_2_df = random.sample(range(100, 200), len(files_df))

df = pd.DataFrame({'file' : files_df,
                 'value_1': value_1_df,
                 'value_2': value_2_df,
                  'used': 0})

Randomly Selecting Files

len_to_run = 3 #change to run for however long you'd like
batch_to_pull = 4
updated_files = df.loc[df.used==0,'file'].unique()

for i in range(len_to_run): #not needed if you only want to run once
    file_to_pull = ''.join(random.sample(updated_files, 1))
    print 'file ' + file_to_pull
    for j in range(batch_to_pull): #pulling 4 values
        updated_value_1 = df.loc[(df.used==0) & (df.file==file_to_pull),'value_1'].unique()
        value_1_to_pull = random.sample(updated_value_1,1)
        print 'value_1 ' + str(value_1_to_pull)
        df.loc[(df.file == file_to_pull) & (df.value_1==value_1_to_pull),'used']=1

file a
value_1 [1]
value_1 [7]
value_1 [5]
value_1 [4]
file d
value_1 [3]
value_1 [2]
value_1 [1]
value_1 [5]
file d
value_1 [7]
value_1 [4]
value_1 [6]
value_1 [9]
🌐
Data Science Parichay
datascienceparichay.com › home › blog › pandas – random sample of columns
Pandas - Random Sample of Columns - Data Science Parichay
October 22, 2020 - The pandas dataframe sample() function can be used to sample columns instead of rows by passing 1 or 'columns' to the axis parameter.
Find elsewhere
🌐
Pandas
pandas.pydata.org › pandas-docs › stable › reference › api › pandas.DataFrame.sample.html
pandas.DataFrame.sample — pandas 3.0.4 documentation
>>> df.sample(frac=2, replace=True, random_state=1) num_legs num_wings num_specimen_seen dog 4 0 2 fish 0 0 8 falcon 2 2 10 falcon 2 2 10 fish 0 0 8 dog 4 0 2 fish 0 0 8 dog 4 0 2 · Using a DataFrame column as weights. Rows with larger value in the num_specimen_seen column are more likely to be sampled.
🌐
datagy
datagy.io › home › pandas tutorials › pandas dataframes › 7 ways to sample data in pandas
7 Ways to Sample Data in Pandas • datagy
December 19, 2022 - In this final section, you'll learn how to use Pandas to sample random columns of your dataframe. This can be done using the Pandas .sample() method, by changing the axis= parameter equal to 1, rather than the default value of 0.
🌐
Pandas
pandas.pydata.org › docs › dev › reference › api › pandas.DataFrame.sample.html
pandas.DataFrame.sample — pandas documentation
>>> df.sample(frac=2, replace=True, random_state=1) num_legs num_wings num_specimen_seen dog 4 0 2 fish 0 0 8 falcon 2 2 10 falcon 2 2 10 fish 0 0 8 dog 4 0 2 fish 0 0 8 dog 4 0 2 · Using a DataFrame column as weights. Rows with larger value in the num_specimen_seen column are more likely to be sampled.
🌐
Spark Code Hub
sparkcodehub.com › pandas › data manipulation › sample
Sample | PANDAS Tutorial | Spark Code Hub
weights: A Series, array, or column name specifying sampling probabilities; weights are normalized to sum to 1. random_state: Integer or tuple for reproducible random sampling; ensures consistent results across runs. ... False (default), retains the original index. ... import pandas as pd # Sample DataFrame data = { 'product': ['Laptop', 'Phone', 'Tablet', 'Monitor', 'Keyboard'], 'revenue': [1000, 800, 300, 600, 200], 'region': ['North', 'South', 'East', 'West', 'North'] } df = pd.DataFrame(data) # Sample 2 random rows df_sampled = df.sample(n=2, random_state=42)
🌐
Skytowner
skytowner.com › explore › randomly_select_rows_based_on_a_condition
Randomly select rows based on a condition from a Pandas DataFrame
To randomly select rows where the value for column B is larger than 5: df.query("B > 5").sample(n=2) A B C · b 2 6 10 · d 4 8 12 · To break this down, df.query("B > 5") returns a DataFrame with rows that satisfy the condition: df.query("B > 5") A B C · b 2 6 10 · c 3 7 11 · d 4 8 12 · The sample(n=2) then randomly selects 2 rows from this DataFrame. Pandas DataFrame | query method ·
🌐
pandas
pandas.pydata.org › pandas-docs › dev › reference › api › pandas.DataFrame.sample.html
pandas.DataFrame.sample — pandas 3.1.0.dev0+974.ge652ee88a5 documentation
>>> df.sample(frac=2, replace=True, random_state=1) num_legs num_wings num_specimen_seen dog 4 0 2 fish 0 0 8 falcon 2 2 10 falcon 2 2 10 fish 0 0 8 dog 4 0 2 fish 0 0 8 dog 4 0 2 · Using a DataFrame column as weights. Rows with larger value in the num_specimen_seen column are more likely to be sampled.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-pandas-dataframe-sample
Pandas Dataframe.sample() | Python - GeeksforGeeks
July 11, 2025 - The sample(n=1) function selects one random row from the DataFrame. DataFrame.sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None) ... frac: Float value, Returns (float value * length of data frame values ) .
🌐
Seaborn Line Plots
marsja.se › home › programming › how to use pandas sample to select rows and columns
How to use Pandas Sample to Select Rows and Columns
February 17, 2025 - ... The easiest way to randomly select rows from a Pandas dataframe is to use the sample() method. For example, if your dataframe is called “df”, df.sample(n=250) will result in that 200 rows being selected randomly.