Skip to main content

Python Pandas DataFrame: sample() method

In Pandas DataFrame there is a sample() method that is used to generate the random row or cloumn from a dataframe
It is used to draw a random sample of items from a Pandas DataFrame.

Syntax

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

Parameter:

  • n: Number of random rows which is to generated.
  • frac: Float value which is fraction of axis items to return.It cannot be used with n.
  • replace: Boolean value, return sample with replacement if True
  • random_state: It is optional.  int value or numpy.random.RandomState, if set to a particular integer, will return same rows as sample in every iteration.
  • axis: for row put 0 and for column 1.

Return:

It can be series or dataframe which is same as caller.

Example

import pandas as pd
df=pd.DataFrame({'Name':['Rohit','Rahul','Alice','John','Joey'],'Age':[16,17,19,15,14],
                 'Height':[150.5,167.9,145.7,152.6,148.7]})

index = ['1', '2', '3', '4', '5']
df.index=index
df.sample()

Output:

  Name Age Height
1 Rohit 16 150.5
Submitted by devanshi.srivastava on November 15, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.