Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn The `sample()` Method | Fetching Data from DataFrames
Pandas: First Steps
course content

Course Content

Pandas: First Steps

Pandas: First Steps

1. Getting Started
2. Basics of Dataframes
3. Fetching Data from DataFrames

book
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;

123456789101112
import 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)
copy
Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 3. ChapterΒ 5

Ask AI

expand
ChatGPT

Ask anything or try one of the suggested questions to begin our chat

course content

Course Content

Pandas: First Steps

Pandas: First Steps

1. Getting Started
2. Basics of Dataframes
3. Fetching Data from DataFrames

book
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;

123456789101112
import 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)
copy
Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 3. ChapterΒ 5
We're sorry to hear that something went wrong. What happened?
some-alt