Write a program in Python to select any random odd index rows in a given DataFrame

PythonPandasServer Side ProgrammingProgramming

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
raja
Published on 11-Feb-2021 10:16:47
Advertisements