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.
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)
01:34:11
Complete Python Pandas Data Science Tutorial! (2024 Updated Edition) ...
06:20
Getting a random sample from your pandas data frame - YouTube
05:08
Pandas Sample | pd.DataFrame.sample() - YouTube
03:04
How to use Pandas to Randomly Select Rows from DataFrame - YouTube
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.
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)
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.
Top answer 1 of 2
1
We can do np.random.choice by doing the index slice
n = len(ratings_top)
idx = np.random.choice(ratings_top.index.values, p=ratings_top['probability'], size=n*0.0007, replace=True)
Then
sample_df = df.loc[idx].copy()
2 of 2
0
from sklearn.model_selection import StratifiedShuffleSplit
n_splits = 1
sss = model_selection.StratifiedShuffleSplit(n_splits=n_splits,
test_size=0.1,
random_state=42)
train_idx, test_idx = list(sss.split(X, y))[0]
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")["...
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.