Write a Python code to select any one random row from a given DataFrame


Input

Assume, sample DataFrame is,

 Id Name
0 1 Adam
1 2 Michael
2 3 David
3 4 Jack
4 5 Peter

Outputput

Random row is
  Id    5
Name Peter

Solution

To solve this, we will follow the below approaches.

  • Define a DataFrame

  • Calculate the number of rows using df.shape[0] and assign to rows variable.

  • set random_row value from randrange method as shown below.

random_row = r.randrange(rows)
  • Apply random_row inside iloc slicing to generate any random row in a DataFrame. It is defined below,

df.iloc[random_row,:]

Example

Let us see the following implementation to get a better understanding.

import pandas as pd
import random as r
data = { 'Id': [1,2,3,4,5],'Name': ['Adam','Michael','David','Jack','Peter']}
df = pd.DataFrame(data)
print("DataFrame is\n", df)
rows = df.shape[0]
print("total number of rows:-", rows)
random_row = r.randrange(rows)
print("print any random row is\n")
print(df.iloc[random_row,:])

Output

DataFrame is
 Id Name
0 1 Adam
1 2 Michael
2 3 David
3 4 Jack
4 5 Peter
total number of rows:- 5
print any random row is
  Id   3
Name David

Updated on: 24-Feb-2021

332 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements