ADVERTISEMENT
ADVERTISEMENT

How to perform random row selection in Pandas DataFrame?

Given a Pandas DataFrame, we have to perform random row selection in Pandas DataFrame.
Submitted by Pranit Sharma, on May 29, 2022

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.

Here, we are going to learn how to learn how to perform random row selection, 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.

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,

# 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:

Example: Perform random row selection

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.