Pandas Sampling and Random Data
Pandas provides rich random sampling capabilities: you can randomly select samples from a dataset as needed and also generate random data.
Random sampling
The sample method
Example
import
pandas
as
pd
import
numpy
as
np
Create a large dataset
df
=
pd.
DataFrame
(
{
"ID"
:
range
(
1
,
1001
)
,
"Value"
: np.
random
.
randn
(
1000
)
}
)
Randomly select 5 rows
(
"5 randomly selected rows:"
)
(
df.
sample
(
5
)
)
(
)
Select 30% of the data
(
"30% randomly selected:"
)
(
df.
sample
(
frac
=
0.3
)
)
(
)
Sampling with replacement
(
"5 rows sampled with replacement:"
)
(
df.
sample
(
5
,
replace
=
True
)
)
Set the random seed
Example
import
pandas
as
pd
import
numpy
as
np
Set a random seed to ensure reproducible results
np.
random
.
seed
(
42
)
df
=
pd.
DataFrame
(
{
"ID"
:
range
(
1
,
11
)
,
"Value"
: np.
random
.
randn
(
10
)
}
)
(
"Using random seed 42:"
)
(
df.
sample
(
3
)
)
Running again with the same seed produces the same result
(
"\nRunning again with the same seed:"
)
np.
random
.
seed
(
42
)
(
df.
sample
(
3
)
)
Random data generation
Example
import
pandas
as
pd
import
numpy
as
np
Generate random integers
(
"Random integers [0, 10):"
)
(
pd.
Series
(
np.
random
.
randint
(
0
,
10
,
5
)
)
)
(
)
Generate random floats
(
"Random floats [0, 1):"
)
(
pd.
Series
(
np.
random
.
random
(
5
)
)
)
(
)
Generate normally distributed random numbers
(
"Normal distribution N(0, 1):"
)
(
pd.
Series
(
np.
random
.
randn
(
5
)
)
)
(
)
Specify the mean and standard deviation
(
"Normal distribution N(10, 2):"
)
(
pd.
Series
(
np.
random
.
normal
(
10
,
2
,
5
)
)
)
(
)
Random choice
choices
=
[
"A"
,
"B"
,
"C"
,
"D"
]
(
"Random choice:"
)
(
pd.
Series
(
np.
random
.
choice
(
choices
,
10
)
)
)
Train/test split
Example
import
pandas
as
pd
import
numpy
as
np
Mock dataset
df
=
pd.
DataFrame
(
{
"feature1"
: np.
random
.
randn
(
100
)
,
"feature2"
: np.
random
.
randn
(
100
)
,
"target"
: np.
random
.
choice
(
[
0
,
1
]
,
100
)
}
)
Split into training and test sets (80% / 20%)
train
=
df.
sample
(
frac
=
0.8
,
random_state
=
42
)
test
=
df.
drop
(
train.
index
)
(
f
"Training set: {len(train)} rows"
)
(
f
"Test set: {len(test)} rows"
)
(
)
Stratified sampling (preserving the target variable ratio)
(
"Stratified sampling:"
)
from
sklearn.
model_selection
import
train_test_split