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

Input

Assume, sample DataFrame is,

 Id Name
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 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
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
Name David