Apply a lambda and call sample with param frac:

In [2]:
df = pd.DataFrame({'a': [1,2,3,4,5,6,7],
                   'b': [1,1,1,0,0,0,0]})
​
grouped = df.groupby('b')
grouped.apply(lambda x: x.sample(frac=0.3))

Out[2]:
     a  b
b        
0 6  7  0
1 2  3  1
Answer from EdChum on Stack Overflow
🌐
Hippocampus's Garden
hippocampus-garden.com › pandas_group_sample
Meet Pandas: Group-wise Sampling | Hippocampus's Garden
October 13, 2020 - Today, I introduce how to sample groups, or group-wise split a dataset. This may help you when you want to avoid data leakage. Suppose we are developing a user-to-item recommender model and have a dataset of 1,000,000 user-item interactions, which include 10,000 unique users, 256 items, and the corresponding conversion flag. Let’s synthesize this dataset with itertools: from itertools import product import numpy as np import pandas as pd str_numbers = "".join(map(str, range(10))) # ['0000', '0001', ..., '9999'] user_ids = list(map("".join, product(str_numbers, repeat=4))) # ['AAAA', 'AAAB', ..., 'DDDD'] item_ids = list(map("".join, product("ABCD", repeat=4))) num_records = 10**6 df = pd.DataFrame({'user_id': np.random.choice(user_ids, num_records), 'item_id': np.random.choice(item_ids, num_records), 'conversion': np.random.choice([0, 1], num_records)}) df
🌐
DataScientYst
datascientyst.com › random-sample-per-group-in-pandas
Random Sample per group in pandas
March 15, 2023 - Here are several ways to sample random rows per group in Pandas: (1) random selection per group df.groupby('continent').apply(lambda x: x.sample(n=3)) (2) random selection per group - different size (df .groupby('continent') .apply(lambda x: ...
🌐
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 - In this brief Pandas tutorial, we learned how to use the sample method. More specifically, we have learned how to: take a random sample of a data using the n (a number of rows) and frac (a percentage of rows) parameters, get reproducible results using a seed (random_state), sample by group, sample using weights, and sample with conditions
🌐
Proclus Academy
proclusacademy.com › blog › stratified_sampling_pandas
What Is Stratified Sampling and How to Do It Using Pandas? | Proclus Academy
July 11, 2022 - So SRS doesn’t work if we want to maintain proportions by a group in the samples. Let’s try what works. We’ll implement Stratified Sampling using Pandas methods groupby() and apply():
Find elsewhere
🌐
Datasciencebyexample
datasciencebyexample.com › 2023 › 03 › 28 › sample-rows-by-sample-in-dataframe
Sampling Rows from a Pandas DataFrame by Group | DataScienceTribe
March 28, 2023 - In this example, we first create a sample dataframe with a ‘vertical’ column and a ‘value’ column. We then group the dataframe by the ‘vertical’ column using the groupby() function. We apply a lambda function to each group that samples up to 100 random rows using the sample() function.
🌐
Machine Learning Plus
machinelearningplus.com › blog › pandas groupby examples
Pandas Groupby Examples - machinelearningplus
March 8, 2022 - This article introduces pandas groupby method, and explains different ways of using it along with practical code examples.
🌐
Medium
melzsydney.medium.com › random-sampling-n-samples-from-each-group-in-a-dataframe-with-many-groups-dd3cfa2d071b
Random sampling n samples from each group, in a DataFrame with many groups.
April 11, 2023 - random_values = df.groupby(‘cea_name’).apply(random_select) # Reset the index of the resulting Series · random_values = random_values.reset_index(drop=True) random_values · Random Sampling · Python Programming · Pandas Dataframe · 7 followers · ·28 following ·
🌐
Linux find Examples
queirozf.com › entries › pandas-dataframe-groupby-examples
Pandas DataFrame: GroupBy Examples
October 18, 2020 - By default, aggregation columns get the name of the column being aggregated over, in this case value Give it a more intuitive name using reset_index(name='new name') After calling groupby(), you can access each group dataframe individually using get_group(). import pandas as pd df = pd.DataFrame({ ...
🌐
GitHub
github.com › pandas-dev › pandas › issues › 31775
Feature Request: Sample method for Groupby objects · Issue #31775 · pandas-dev/pandas
February 7, 2020 - Many times it is desirable to be able to iterate over a small number of groups of a group by object. Currently there is no direct way to get a random sample of groups. Similar to DataFrame.sample method, can we have Groupby.sample method which ...
Author   pandas-dev
🌐
CSDN
devpress.csdn.net › python › 63046130c67703293080c1ba.html
Python Pandas Choosing Random Sample of Groups from Groupby_python_Mangs-Python
August 23, 2022 - In [337]: df = pd.DataFrame({'some_key': [0,1,2,3,0,1,2,3,0,1,2,3], 'val': [1,2,3,4,1,5,1,5,1,6,7,8]}) In [338]: print df[df.some_key.isin(random.sample(df.some_key.unique(),2))].groupby('some_key').mean() val some_key 0 1.000000 2 3.666667 ... In [358]: df = pd.DataFrame({'some_key1':[0,1,2,3,0,1,2,3,0,1,2,3], 'some_key2':[0,0,0,0,1,1,1,1,2,2,2,2], 'val': [1,2,3,4,1,5,1,5,1,6,7,8]}) In [359]: gby = df.groupby(['some_key1', 'some_key2']) In [360]: print gby.mean().ix[random.sample(gby.indices.keys(),2)] val some_key1 some_key2 1 1 5 3 2 8
🌐
Pydocs
pydocs.github.io › p › pandas › 1.4.2 › api › pandas.core.groupby.groupby.GroupBy.sample.html
GroupBy.sample
ParametersReturnsBackRef sample(self, n: 'int | None' = None, frac: 'float | None' = None, replace: 'bool' = False, weights: 'Sequence | Series | None' = None, random_state: 'RandomState | None' = None) You can use random_state for reproducibility. ... Number of items to return for each group.