The `sample()` Method
The sample()
method returns a random row from the DataFrame by default.
There are two optional named parameters which can be used to specify how many random rows to fetch:
n
: Specifies the exact number of random rows to fetch;frac
: Specifies the fraction or percentage of the total rows to fetch. For example,frac=0.2
will return 20% of the total rows;
123456789101112import pandas as pd # Sample DataFrame df = pd.DataFrame({ 'Coffee': ['Espresso', 'Latte', 'Cappuccino', 'Americano', 'Macchiato'], 'Price': [2.5, 3.5, 3.0, 2.8, 3.2], 'Availability': ['Yes', 'Yes', 'Yes', 'Yes', 'No'] }) print("Get 2 random rows from the DataFrame:") random_rows = df.sample(n=2) print(random_rows)
Everything was clear?
Thanks for your feedback!
SectionΒ 3. ChapterΒ 5
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Suggested prompts:
Ask me questions about this topic
Summarize this chapter
Show real-world examples
Awesome!
Completion rate improved to 2.7
The `sample()` Method
Swipe to show menu
The sample()
method returns a random row from the DataFrame by default.
There are two optional named parameters which can be used to specify how many random rows to fetch:
n
: Specifies the exact number of random rows to fetch;frac
: Specifies the fraction or percentage of the total rows to fetch. For example,frac=0.2
will return 20% of the total rows;
123456789101112import pandas as pd # Sample DataFrame df = pd.DataFrame({ 'Coffee': ['Espresso', 'Latte', 'Cappuccino', 'Americano', 'Macchiato'], 'Price': [2.5, 3.5, 3.0, 2.8, 3.2], 'Availability': ['Yes', 'Yes', 'Yes', 'Yes', 'No'] }) print("Get 2 random rows from the DataFrame:") random_rows = df.sample(n=2) print(random_rows)
Everything was clear?
Thanks for your feedback!
SectionΒ 3. ChapterΒ 5