w3resource

Pandas DataFrame: sample() function

DataFrame - sample() function

The sample() function is used to get a random sample of items from an axis of object.

Syntax:

DataFrame.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:


Download the Pandas DataFrame Notebooks from here.

Previous: DataFrame - rename_axis() function
Next: DataFrame - set_axis() function



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://www.w3resource.com/pandas/dataframe/dataframe-sample.php