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.
🌐
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
🌐
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.
🌐
Vultr Docs
docs.vultr.com › python › third-party › pandas › DataFrame › sample
Python Pandas DataFrame sample() - Random Row or Column Selection | Vultr Docs
December 24, 2024 - The sample() function in the Pandas library offers a powerful way to randomly select rows or columns from a DataFrame, which can be crucial for creating training and testing datasets, or for performing data integrity checks.
🌐
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.
🌐
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.
🌐
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 - The easiest way to generate random set of rows with Python and Pandas is by: df.sample. By default returns one random row from DataFrame: ... It can be applied for rows by using axis=1 as shown below. ... If you like to get a fraction (or percentage of your data) than you can use parameter fraction. In the example below dataset has 5000 rows and 0.001 will return exactly 5 random rows: # The fraction of rows and columns: frac df.sample(frac=0.001)
Find elsewhere
🌐
Scaler
scaler.com › home › topics › what is pandas dataframe sample() method?
What is Pandas DataFrame sample() Method? - Scaler Topics
May 4, 2023 - The pandas sample() method is used ... rows or columns from pandas dataframe. If applied to a pandas Series, this method returns a subset of random items from that Series. The most common usage of the pandas sample() method is to get a sample of random rows from a pandas data frame.
🌐
W3Schools
w3schools.com › python › pandas › ref_df_sample.asp
Pandas DataFrame sample() Method
import pandas as pd df = pd.read_csv('data.csv') print(df.sample()) Try it Yourself » · The sample() method returns a specified number of random rows. The sample() method returns 1 row if a number is not specified.
🌐
Pandas
pandas.pydata.org › pandas-docs › version › 0.24.2 › reference › api › pandas.DataFrame.sample.html
pandas.DataFrame.sample — pandas 0.24.2 documentation
Rows with larger value in the num_specimen_seen column are more likely to be sampled. >>> df.sample(n=2, weights='num_specimen_seen', random_state=1) num_legs num_wings num_specimen_seen falcon 2 2 10 fish 0 0 8 · index · modules | next | previous | pandas 0.24.2 documentation » ·
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]
🌐
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.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-pandas-dataframe-sample
Pandas Dataframe.sample() | Python - GeeksforGeeks
July 11, 2025 - axis: 0 or 'row' for Rows and 1 or 'column' for Columns. Return Type: New object of same type as caller. To download the CSV file used, Click Here. In this example, we generate a random sample consisting of 25% of the entire DataFrame by using ...
🌐
Pandas
pandas.pydata.org › pandas-docs › version › 1.5 › reference › api › pandas.core.groupby.DataFrameGroupBy.sample.html
pandas.core.groupby.DataFrameGroupBy.sample — pandas 1.5.3 documentation
Select one row at random for each distinct value in column a. The random_state argument can be used to guarantee reproducibility: >>> df.groupby("a").sample(n=1, random_state=1) a b 4 black 4 2 blue 2 1 red 1 · Set frac to sample fixed proportions rather than counts: >>> df.groupby("a")["...
🌐
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.
🌐
Pandas
pandas.pydata.org › pandas-docs › version › 0.25.0 › reference › api › pandas.DataFrame.sample.html
pandas.DataFrame.sample — pandas 0.25.0 documentation
>>> df.sample(frac=0.5, replace=True, random_state=1) num_legs num_wings num_specimen_seen dog 4 0 2 fish 0 0 8 · Using a DataFrame column as weights.