6.6. DataFrame Sample

  • .sample(n=5)

  • .sample(n=5, replace=True)

  • .sample(frac=.5)

  • .sample(frac=1/2)

  • .head(n=5)

  • .tail(n=5)

  • .reset_index(drop=True)

6.6.1. SetUp

>>> import pandas as pd
>>> import numpy as np
>>>
>>>
>>> df = pd.DataFrame([
...     {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30},
...     {'firstname': 'Bob', 'lastname': 'Blackthorn', 'age': 31},
...     {'firstname': 'Carol', 'lastname': 'Corn', 'age': 32},
... ])
>>>
>>> df
  firstname    lastname  age
0     Alice     Apricot   30
1       Bob  Blackthorn   31
2     Carol        Corn   32

6.6.3. Tail

  • DataFrame.tail(n) - return last n rows

>>> df.tail(2)
  firstname    lastname  age
1       Bob  Blackthorn   31
2     Carol        Corn   32
>>> df.tail(n=2)
  firstname    lastname  age
1       Bob  Blackthorn   31
2     Carol        Corn   32

6.6.4. Sample

>>> np.random.seed(0)
>>> df.sample(n=2)
  firstname    lastname  age
2     Carol        Corn   32
1       Bob  Blackthorn   31
>>> np.random.seed(0)
>>> df.sample(frac=1/2)
  firstname    lastname  age
2     Carol        Corn   32
1       Bob  Blackthorn   31
>>> np.random.seed(0)
>>> df.sample(frac=1.00, replace=True)
  firstname    lastname  age
0     Alice     Apricot   30
1       Bob  Blackthorn   31
0     Alice     Apricot   30

6.6.5. Reset Index

  • DataFrame.reset_index(drop=True) - reset index to default integer index

>>> np.random.seed(0)
>>> df.sample(frac=1.00)
  firstname    lastname  age
2     Carol        Corn   32
1       Bob  Blackthorn   31
0     Alice     Apricot   30
>>> np.random.seed(0)
>>> df.sample(frac=1.00).reset_index(drop=True)
  firstname    lastname  age
0     Carol        Corn   32
1       Bob  Blackthorn   31
2     Alice     Apricot   30

6.6.6. Assignments

# %% About
# - Name: DataFrame Sample
# - Difficulty: easy
# - Lines: 4
# - Minutes: 3

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Read data from `DATA` as `df: pd.DataFrame`
# 2. Set all rows in random order
# 3. Reset index without leaving a backup of the old one
# 4. Define `result` with last 10 rows
# 5. Run doctests - all must succeed

# %% Polish
# 1. Wczytaj dane z `DATA` jako `df: pd.DataFrame`
# 2. Ustaw wszystkie wiersze w losowej kolejności
# 3. Zresetuj index nie pozostawiając kopii zapasowej starego
# 4. Zdefiniuj `result` z ostatnimi 10 wierszami
# 5. Uruchom doctesty - wszystkie muszą się powieść

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0

>>> assert sys.version_info >= (3, 9), \
'Python has an is invalid version; expected: `3.9` or newer.'

>>> pd.set_option('display.width', 500)
>>> pd.set_option('display.max_columns', 10)
>>> pd.set_option('display.max_rows', 10)

>>> assert 'result' in globals(), \
'Variable `result` is not defined; assign result of your program to it.'

>>> assert result is not Ellipsis, \
'Variable `result` has an invalid value; assign result of your program to it.'

>>> assert type(result) is pd.DataFrame, \
'Variable `result` has an invalid type; expected: `pd.DataFrame`.'

>>> result  # doctest: +NORMALIZE_WHITESPACE
                       Name        Country Gender                                            Flights  Total Flights Total Flight Time (ddd:hh:mm)
557  Thomas Marshburn, M.D.  United States    Man               STS-127 (2009), Soyuz TMA-07M (2012)              2                     161:07:03
558           Michael Baker  United States    Man  STS-43 (1991), STS-52 (1992), STS-68 (1994), S...              4                     040:03:04
559            Rick Husband  United States    Man                      STS-96 (1999), STS-107 (2003)              2                     025:13:33
560     Svetlana Savitskaya   Soviet Union  Woman                Soyuz T-7 (1982), Soyuz T-12 (1984)              2                     019:17:07
561   Charles "Pete" Conrad  United States    Man  Gemini 5 (1965), Gemini 11 (1966), Apollo 12 (...              4                     049:03:38
562     Lawrence J. DeLucas  United States    Man                                      STS-50 (1992)              1                     013:19:30
563      Aleksandr Laveykin   Soviet Union    Man                                  Soyuz TM-2 (1987)              1                     174:03:25
564           Owen Garriott  United States    Man                      Skylab 3 (1973), STS-9 (1983)              2                     069:17:56
565             Ivan Vagner         Russia    Man                                 Soyuz MS-16 (2020)              1                     145:04:14
566        Yuri Malenchenko         Russia    Man  Soyuz TM-19 (1994), STS-106 (2000), Soyuz TMA-...              6                     826:09:22
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports
import pandas as pd
import numpy as np

# %% Types
result: pd.DataFrame

# %% Data
np.random.seed(0)

DATA = 'https://python3.info/_static/astro-database.csv'

# %% Result
result = ...