Pandas Series: sample() function
Random items from an axis of Pandas object
The sample() function is used to get a random sample of items from an axis of object.
Syntax:
Series.sample(self, n=None, frac=None, replace=False, weights=None, random_state=None, axis=None)
Parameters:
Name | Description | Type/Default Value | Required / Optional |
---|---|---|---|
n | Number of items from axis to return. Cannot be used with frac. Default = 1 if frac = None. | int | optional |
frac | Fraction of axis items to return. Cannot be used with n. | float | optional |
replace | Sample with or without replacement. | bool Default Value: False |
Required |
weights | Default ‘None’ results in equal probability weighting. If passed a Series, will align with target object on index. Index values in weights not found in sampled object will be ignored and index values in sampled object not in weights will be assigned weights of zero. If called on a DataFrame, will accept the name of a column when axis = 0. Unless weights are a Series, weights must be same length as axis being sampled. If weights do not sum to 1, they will be normalized to sum to 1. Missing values in the weights column will be treated as zero. Infinite values not allowed. | str or ndarray-like | optional |
random_state | Seed for the random number generator (if int), or numpy RandomState object. | int or numpy.random.RandomState, | optional |
axis | Axis to sample. Accepts axis number or name. Default is stat axis for given data type (0 for Series and DataFrames). | int or string | optional |
Returns: Series or DataFrame
A new object of same type as caller containing n items randomly sampled from the caller object.
Example - Generate a DataFrame with default index:
Python-Pandas Code:
import numpy as np
import pandas as pd
df = pd.DataFrame({'num_legs': [2, 4, 8, 0],
'num_wings': [2, 0, 0, 0],
'num_specimen_seen': [8, 2, 1, 6]},
index=['sparrow', 'cat', 'spider', 'snake'])
df
Output:
num_legs num_wings num_specimen_seen sparrow 2 2 8 cat 4 0 2 spider 8 0 1 snake 0 0 6
Example - Extract 3 random elements from the Series df['num_legs']: Note that we use random_state to ensure the reproducibility of the examples:
Python-Pandas Code:
import numpy as np
import pandas as pd
df = pd.DataFrame({'num_legs': [2, 4, 8, 0],
'num_wings': [2, 0, 0, 0],
'num_specimen_seen': [8, 2, 1, 6]},
index=['sparrow', 'cat', 'spider', 'snake'])
df['num_legs'].sample(n=3, random_state=1)
Output:
snake 0 spider 8 sparrow 2 Name: num_legs, dtype: int64
Example - A random 50% sample of the DataFrame with replacement:
Python-Pandas Code:
import numpy as np
import pandas as pd
df = pd.DataFrame({'num_legs': [2, 4, 8, 0],
'num_wings': [2, 0, 0, 0],
'num_specimen_seen': [8, 2, 1, 6]},
index=['sparrow', 'cat', 'spider', 'snake'])
df.sample(frac=0.5, replace=True, random_state=1)
Output:
num_legs num_wings num_specimen_seen cat 4 0 2 snake 0 0 6
Example - Using a DataFrame column as weights. Rows with larger value in the num_specimen_seen column are more likely to be sampled:
Python-Pandas Code:
import numpy as np
import pandas as pd
df = pd.DataFrame({'num_legs': [2, 4, 8, 0],
'num_wings': [2, 0, 0, 0],
'num_specimen_seen': [8, 2, 1, 6]},
index=['sparrow', 'cat', 'spider', 'snake'])
df.sample(n=2, weights='num_specimen_seen', random_state=1)
Output:
num_legs num_wings num_specimen_seen sparrow 2 2 8 snake 0 0 6
Previous: Generate a new Pandas series with the index reset
Next: Series-set_axis() function
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/pandas/series/series-sample.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics