
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- Related Articles
- Write a program in Python to select any random odd index rows in a given DataFrame
- Write a Python code to rename the given axis in a dataframe
- Write a Python code to filter palindrome names in a given dataframe
- Write a Python code to swap last two rows in a given dataframe
- Python Pandas - How to select rows from a DataFrame by passing row label
- Write a Python code to fill all the missing values in a given dataframe
- Write a Python code to combine two given series and convert it to a dataframe
- Select a random row in MySQL
- MySQL query to select one specific row and another random row?\n
- Python Pandas - How to delete a row from a DataFrame
- Write a Python code to find the second lowest value in each column in a given dataframe
- Python - How to select a column from a Pandas DataFrame
- Write a program in Python to remove one or more than one columns in a given DataFrame
- Python - Select multiple columns from a Pandas dataframe
- Write a Python code to read JSON data from a file and convert it to dataframe, CSV files

Advertisements