Pandas DataFrame: sample() function

DataFrame - sample() function

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


DataFrame.sample(self, n=None, frac=None, replace=False, weights=None, random_state=None, axis=None)


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


Download the Pandas DataFrame Notebooks from here.

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

Follow us on Facebook and Twitter for latest update.