
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Select Random Row from DataFrame in Python
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
Advertisements