Home »
Python »
Python Programs
How to perform random row selection in Pandas DataFrame?
Given a Pandas DataFrame, we have to perform random row selection in Pandas DataFrame.
By Pranit Sharma Last updated : September 21, 2023
Rows in pandas are the different cell (column) values which are aligned horizontally and also provides uniformity. Each row can have same or different value. Rows are generally marked with the index number but in pandas we can also assign index name according to the needs. In pandas, we can create, read, update and delete a column or row value.
Performing random row selection in Pandas DataFrame
For this purpose, we have a easy and direct method called pandas.DataFrame.sample() method, which iterates over the DataFrame and selects a row from the DataFrame randomly.
Note
To work with pandas, we need to import pandas package first, below is the syntax:
import pandas as pd
Let us understand with the help of an example,
Python program to perform random row selection in Pandas DataFrame
# Import pandas Package
import pandas as pd
# Creating dictionary
d = {
'CSK':['Dhoni', 'Jadeja', 'Raydu','Uthappa', 'Gaiakwad', 'Bravo'],
'Age':[40, 33, 36, 36, 25, 38]
}
# Creating a Dataframe
df = pd.DataFrame(d,index = ['a', 'b', 'c', 'd', 'e', 'f'])
print("Created Dataframe:\n", df,"\n")
# Selecting a row randomly
print("Randomly selected row:\n",df.sample())
Output
The output of the above program is:
Python Pandas Programs »