 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
Write a program in Python to select any random odd index rows in a given DataFrame
Assume, you have a dataframe,
DataFrame is: id mark age 0 1 70 12 1 2 60 13 2 3 40 12 3 4 50 13 4 5 80 12 5 6 90 13 6 7 60 12
And, the result for selecting any random odd index row is,
Random odd index row is: id 4 mark 50 age 13
Solution
To solve this, we will follow the steps given below −
- Define a dataframe 
- Create an empty list to append odd index values 
- Create a for loop to access all the index. It is defined below, 
for i in df.index.values:
- Create an if condition to check the odd index. If it is matches, then append the values to the list, 
if(i%2==1): l.append(i)
- Generate any one random value from the list and store it random_index 
random_index = rand.choice(l)
- Finally, print the odd index row using the iloc. 
df.iloc[random_index]
Example
Let’s see the below implementation to get a better understanding −
import pandas as pd import random as rand df = pd.DataFrame({'id': [1,2,3,4,5,6,7],                   'mark': [70,60,40,50,80,90,60],                   'age':[12,13,12,13,12,13,12]                   }) print("DataFrame is:\n",df) l = [] for i in df.index.values:    if(i%2==1):       l.append(i) random_index = rand.choice(l) print("Random odd index row is: \n", df.iloc[random_index]) Output
DataFrame is: id mark age 0 1 70 12 1 2 60 13 2 3 40 12 3 4 50 13 4 5 80 12 5 6 90 13 6 7 60 12 Random odd index row is: id 4 mark 50 age 13 Name: 3, dtype: int64
Advertisements
 