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 OverflowPandas
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.
06:20
Getting a random sample from your pandas data frame - YouTube
05:08
Pandas Sample | pd.DataFrame.sample() - YouTube
16:13
Select Random Rows or Columns in Pandas with sample() – Quick ...
07:24
How to Use sample() to Randomly Select Data from DataFrames | PySpark ...
03:04
How to use Pandas to Randomly Select Rows from DataFrame - YouTube
Dask
docs.dask.org › en › latest › generated › dask.dataframe.DataFrame.sample.html
dask.dataframe.DataFrame.sample — Dask documentation
DataFrame.sample(n=None, frac=None, replace=False, random_state=None)# Random sample of items · Parameters: nint, optional · Number of items to return is not supported by dask. Use frac instead. fracfloat, optional · Approximate fraction of items to return.
Apache
spark.apache.org › docs › latest › api › python › reference › pyspark.sql › api › pyspark.sql.DataFrame.sample.html
pyspark.sql.DataFrame.sample — PySpark 4.2.0 documentation
This is not guaranteed to provide exactly the fraction specified of the total count of the given DataFrame. fraction is required and, withReplacement and seed are optional. ... >>> df = spark.range(0, 10, 1, 1) >>> df.sample(0.5, 3).count() 7 >>> df.sample(fraction=0.5, seed=3).count() 4 >>> df.sample(withReplacement=True, fraction=0.5, seed=3).count() 2 >>> df.sample(1.0).count() 10 >>> df.sample(fraction=1.0).count() 10 >>> df.sample(False, fraction=1.0).count() 10
W3Schools
w3schools.com › python › pandas › ref_df_sample.asp
Pandas DataFrame sample() Method
Note: The column names will also be returned, in addition to the sample rows. dataframe.sample(n, frac, replace, weights, random_state, axis)
Top answer 1 of 4
35
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)
2 of 4
13
You can use DataFrameGroupBy.sample method as follwing:
sample_df = df.groupby("target").sample(n=5000, random_state=1)
Top answer 1 of 5
74
You can use the sample method*:
In [11]: df = pd.DataFrame([[1, 2], [3, 4], [5, 6], [7, 8]], columns=["A", "B"])
In [12]: df.sample(2)
Out[12]:
A B
0 1 2
2 5 6
In [13]: df.sample(2)
Out[13]:
A B
3 7 8
0 1 2
*On one of the section DataFrames.
Note: If you have a larger sample size that the size of the DataFrame this will raise an error unless you sample with replacement.
In [14]: df.sample(5)
ValueError: Cannot take a larger sample than population when 'replace=False'
In [15]: df.sample(5, replace=True)
Out[15]:
A B
0 1 2
1 3 4
2 5 6
3 7 8
1 3 4
2 of 5
12
One solution is to use the choice function from numpy.
Say you want 50 entries out of 100, you can use:
import numpy as np
chosen_idx = np.random.choice(1000, replace=False, size=50)
df_trimmed = df.iloc[chosen_idx]
This is of course not considering your block structure. If you want a 50 item sample from block i for example, you can do:
import numpy as np
block_start_idx = 1000 * i
chosen_idx = np.random.choice(1000, replace=False, size=50)
df_trimmed_from_block_i = df.iloc[block_start_idx + chosen_idx]
Polars
docs.pola.rs › api › python › stable › reference › dataframe › api › polars.DataFrame.sample.html
polars.DataFrame.sample — Polars documentation
Seed for the random number generator. If set to None (default), a random seed is generated for each time the sample is called. ... >>> df = pl.DataFrame( ... { ... "foo": [1, 2, 3], ... "bar": [6, 7, 8], ... "ham": ["a", "b", "c"], ...
Pandas
pandas.pydata.org › pandas-docs › version › 1.5 › reference › api › pandas.DataFrame.sample.html
pandas.DataFrame.sample — pandas 1.5.3 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.
Codegive
codegive.com › blog › pandas_random_sample.php
Pandas Random Sample: Unlock Powerful Insights & Build Robust Models (2024) with Smarter Data Selection!
Master pandas random sample for efficient, unbiased data selection. Learn to sample DataFrames & Series with replacement, weights, and reproducible results.
Google Groups
groups.google.com › g › xarray › c › z_CGrqoopLA
Random sampling like pandas.DataFrame.sample()
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sample.html · Is there an equivalent in xarray? Searching has revealed nothing. thanks, Emma · unread, May 5, 2020, 12:21:29 PM5/5/20 · · · · Reply to author · Sign in to reply to author ·
GeeksforGeeks
geeksforgeeks.org › r language › take-random-samples-from-a-data-frame-in-r-programming-sample_n-function
Take Random Samples from a Data Frame in R Programming - sample_n() Function - GeeksforGeeks
July 15, 2025 - # R program to collect sample data ... a data frame d <- data.frame( name = c("Abhi", "Bhavesh", "Chaman", "Dimri"), age = c(7, 5, 9, 16), ht = c(46, NA, NA, 69), school = c("yes", "yes", "no", "no") ) # Printing three rows sample_n(d, ...
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 post, you learned all the different ways in which you can sample a Pandas Dataframe. You learned how to use the Pandas .sample() method, including how to return a set number of rows or a fraction of your dataframe. You also learned how to apply weights to your samples and how to select rows iteratively at a constant rate.
Statology
statology.org › home › pandas: how to sample rows with replacement
Pandas: How to Sample Rows with Replacement
March 20, 2023 - import pandas as pd #create DataFrame df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], 'points': [18, 22, 19, 14, 14, 11, 20, 28], 'assists': [5, 7, 7, 9, 12, 9, 9, 4], 'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]}) #view DataFrame print(df) team points assists rebounds 0 A 18 5 11 1 B 22 7 8 2 C 19 7 10 3 D 14 9 6 4 E 14 12 6 5 F 11 9 5 6 G 20 9 9 7 H 28 4 12 · Suppose we use the sample() function to randomly select a sample of rows:
Ryan Nolan Data
ryanandmattdatascience.com › home › python pandas › pandas sample
Pandas sample(): Random Sampling Made Simple in Python
June 15, 2025 - Learn how to use pandas sample() to randomly select rows from a DataFrame. Includes examples for sampling with/without replacement and setting random state.
W3Schools
w3schools.com › python › pandas › pandas_dataframes.asp
Pandas DataFrames
As you can see from the result above, the DataFrame is like a table with rows and columns.