6.23. DataFrame Mapping
DataFrame.map()- Map values of Series according to input mapping or functionDataFrame.apply()- Apply a function along an axis of the DataFrameDataFrame.pipe()- Apply chainable functions that expect Series or DataFrames
6.23.1. SetUp
>>> import pandas as pd
>>>
>>> df = pd.DataFrame([
... {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30},
... {'firstname': 'Bob', 'lastname': 'Blackthorn', 'age': 31},
... {'firstname': 'Carol', 'lastname': 'Corn', 'age': 32},
... ], index=['a', 'b', 'c'])
>>> df
firstname lastname age
a Alice Apricot 30
b Bob Blackthorn 31
c Carol Corn 32
6.23.2. Map
Works only on Series
Argument:
dict,Series, orCallableWorks element-wise on a Series
Operate on one element at time
When passed a dictionary/Series will map elements based on the keys in that dictionary/Series, missing values will be recorded as
NaNin the outputIs optimised for elementwise mappings and transformation
Operations that involve dictionaries or Series will enable pandas to use faster code paths for better performance [5]
>>> def upper(x):
... if isinstance(x, str):
... return x.upper()
... return x
>>>
>>> df.map(upper)
firstname lastname age
a ALICE APRICOT 30
b BOB BLACKTHORN 31
c CAROL CORN 32
>>> df.map(str)
firstname lastname age
a Alice Apricot 30
b Bob Blackthorn 31
c Carol Corn 32
6.23.3. Apply
Works on both Series and DataFrame
Argument:
CallableOn Series: operate on one element at time
On DataFrame: elementwise but also row / column basis
Suited to more complex operations and aggregation
The behaviour and return value depends on the function
Returns a scalar for aggregating operations, Series otherwise. Similarly for
DataFrame.applyHas fastpaths when called with certain NumPy functions such as
mean,sum, etc. [5]
>>> df.apply(str)
firstname a Alice\nb Bob\nc Carol\nName: firs...
lastname a Apricot\nb Blackthorn\nc C...
age a 30\nb 31\nc 32\nName: age, dtype: i...
dtype: str
6.23.4. Differentiation
DataFrame.map- Element-wise, operates on one element at timeDataFrame.applyWorks on a row / column basis, operates on entire rows or columns at a time
Definition:
mapdefined onSeriesandDataFrame
applydefined onSeriesandDataFrame
Argument type:
maptakesdict,Series,Callable
applytakesCallableonly
Behavior:
mapelementwise
applyelementwise but is suited to more complex operations and aggregation; the behaviour and return value depends on the function
Use Case:
mapis good for elementwise transformations across multiple rows/columns (e.g.,df[['A', 'B', 'C']].applymap(str.strip))
applyis for applying any function that cannot be vectorised (e.g.,df['sentences'].apply(nltk.sent_tokenize))
Footnotes [5]:
mapis optimised for elementwise mappings and transformation. Operations that involve dictionaries or Series will enable pandas to use faster code paths for better performance. When passed a dictionary/Series will map elements based on the keys in that dictionary/Series; missing values will be recorded asNaNin the output [1]
applyreturns a scalar for aggregating operations, Series otherwise. Note thatapplyalso has fastpaths when called with certain NumPy functions such asmean,sum, etc. [3]
6.23.5. References
6.23.6. Assignments
# %% About
# - Name: DataFrame Mapping Split
# - Difficulty: easy
# - Lines: 5
# - Minutes: 5
# %% 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. Parse data in `datetime` column as `datetime` object
# 3. Split column `datetime` with into two separate: date and time columns
# 4. Run doctests - all must succeed
# %% Polish
# 1. Wczytaj dane z `DATA` jako `df: pd.DataFrame`
# 2. Sparsuj dane w kolumnie `datetime` jako obiekty `datetime`
# 3. Podziel kolumnę z `datetime` na dwie osobne: datę i czas
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% Expected
# >>> result # doctest: +NORMALIZE_WHITESPACE
# id period datetime network item type duration date time
# 0 0 1999-11 1999-10-15 06:58:00 T-Mobile data data 34.5 1999-10-15 06:58:00
# 1 1 1999-11 1999-10-15 06:58:00 Orange call mobile 13.0 1999-10-15 06:58:00
# 2 2 1999-11 1999-10-15 14:46:00 Play call mobile 23.0 1999-10-15 14:46:00
# 3 3 1999-11 1999-10-15 14:48:00 Plus call mobile 4.0 1999-10-15 14:48:00
# 4 4 1999-11 1999-10-15 17:27:00 T-Mobile call mobile 4.0 1999-10-15 17:27:00
# .. ... ... ... ... ... ... ... ... ...
# 825 825 2000-03 2000-03-13 00:38:00 AT&T sms international 1.0 2000-03-13 00:38:00
# 826 826 2000-03 2000-03-13 00:39:00 Orange sms mobile 1.0 2000-03-13 00:39:00
# 827 827 2000-03 2000-03-13 06:58:00 Orange data data 34.5 2000-03-13 06:58:00
# 828 828 2000-03 2000-03-14 00:13:00 AT&T sms international 1.0 2000-03-14 00:13:00
# 829 829 2000-03 2000-03-14 00:16:00 AT&T sms international 1.0 2000-03-14 00:16:00
# <BLANKLINE>
# [830 rows x 9 columns]
# %% Hints
# - `pd.Series.dt.date`
# - `pd.Series.dt.time`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python has an is invalid version; expected: `3.9` or newer.'
>>> 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`.'
>>> pd.set_option('display.max_columns', 50)
>>> pd.set_option('display.max_rows', 200)
>>> pd.set_option('display.width', 500)
>>> pd.set_option('display.memory_usage', 'deep')
>>> pd.set_option('display.precision', 4)
>>> result # doctest: +NORMALIZE_WHITESPACE
id period datetime network item type duration date time
0 0 1999-11 1999-10-15 06:58:00 T-Mobile data data 34.5 1999-10-15 06:58:00
1 1 1999-11 1999-10-15 06:58:00 Orange call mobile 13.0 1999-10-15 06:58:00
2 2 1999-11 1999-10-15 14:46:00 Play call mobile 23.0 1999-10-15 14:46:00
3 3 1999-11 1999-10-15 14:48:00 Plus call mobile 4.0 1999-10-15 14:48:00
4 4 1999-11 1999-10-15 17:27:00 T-Mobile call mobile 4.0 1999-10-15 17:27:00
.. ... ... ... ... ... ... ... ... ...
825 825 2000-03 2000-03-13 00:38:00 AT&T sms international 1.0 2000-03-13 00:38:00
826 826 2000-03 2000-03-13 00:39:00 Orange sms mobile 1.0 2000-03-13 00:39:00
827 827 2000-03 2000-03-13 06:58:00 Orange data data 34.5 2000-03-13 06:58:00
828 828 2000-03 2000-03-14 00:13:00 AT&T sms international 1.0 2000-03-14 00:13:00
829 829 2000-03 2000-03-14 00:16:00 AT&T sms international 1.0 2000-03-14 00:16:00
<BLANKLINE>
[830 rows x 9 columns]
"""
# %% 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
# %% Types
result: pd.DataFrame
# %% Data
DATA = 'https://python3.info/_static/phones-pl.csv'
# %% Result
result = ...
# %% About
# - Name: DataFrame Mapping Translate
# - Difficulty: easy
# - Lines: 5
# - Minutes: 5
# %% 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. Convert Polish month names to English
# 3. Parse dates to `datetime` objects
# 4. Select columns ['firstname', 'lastname', 'birthdate']
# 5. Run doctests - all must succeed
# %% Polish
# 1. Wczytaj dane z `DATA` jako `df: pd.DataFrame`
# 2. Przekonwertuj polskie nazwy miesięcy na angielskie
# 3. Sparsuj daty do obiektów `datetime`
# 4. Wybierz kolumny ['firstname', 'lastname', 'birthdate']
# 5. Uruchom doctesty - wszystkie muszą się powieść
# %% Expected
# >>> result[['firstname', 'lastname', 'birthdate']] # doctest: +NORMALIZE_WHITESPACE
# firstname lastname birthdate
# 0 Mark Watney 1994-10-12
# 1 Melissa Lewis 1995-07-07
# 2 Rick Martinez 1996-01-21
# 3 Alex Vogel 1994-11-15
# 4 Beth Johanssen 2006-05-09
# 5 Chris Beck 1999-08-02
# %% Hints
# - `pd.Series.replace(regex=True)`
# - `pd.to_datetime()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python has an is invalid version; expected: `3.9` or newer.'
>>> 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`.'
>>> pd.set_option('display.max_columns', 50)
>>> pd.set_option('display.max_rows', 200)
>>> pd.set_option('display.width', 500)
>>> pd.set_option('display.memory_usage', 'deep')
>>> pd.set_option('display.precision', 4)
>>> result[['firstname', 'lastname', 'birthdate']] # doctest: +NORMALIZE_WHITESPACE
firstname lastname birthdate
0 Mark Watney 1994-10-12
1 Melissa Lewis 1995-07-07
2 Rick Martinez 1996-01-21
3 Alex Vogel 1994-11-15
4 Beth Johanssen 2006-05-09
5 Chris Beck 1999-08-02
"""
# %% 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
# %% Types
result: pd.DataFrame
# %% Data
DATA = 'https://python3.info/_static/martian-pl.csv'
MONTHS_PLEN = {'styczeń': 'January',
'luty': 'February',
'marzec': 'March',
'kwiecień': 'April',
'maj': 'May',
'czerwiec': 'June',
'lipiec': 'July',
'sierpień': 'August',
'wrzesień': 'September',
'październik': 'October',
'listopad': 'November',
'grudzień': 'December'}
# %% Result
result = ...
# %% About
# - Name: DataFrame Mapping Month
# - Difficulty: easy
# - Lines: 10
# - Minutes: 8
# %% 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. Add column `year` and `month` by parsing `period` column
# 3. Month name must be a string month name, not a number (i.e.: 'January', 'May')
# 4. Example: if `period` column is "2015-01", then `year`: 2015, `month`: January
# 5. Run doctests - all must succeed
# %% Polish
# 1. Wczytaj dane z `DATA` jako `df: pd.DataFrame`
# 2. Dodaj kolumnę `year` i `month` poprzez sparsowanie kolumny `period`
# 3. Nazwa miesiąca musi być ciągiem znaków, a nie liczbą (i.e. 'January', 'May')
# 4. Example: jeżeli kolumna `period` jest "2015-01", to `year`: 2015, `month`: January
# 5. Uruchom doctesty - wszystkie muszą się powieść
# %% Expected
# >>> result # doctest: +NORMALIZE_WHITESPACE
# id period datetime network item type duration year month
# 0 0 1999-11 1999-10-15 06:58 T-Mobile data data 34.5 1999 November
# 1 1 1999-11 1999-10-15 06:58 Orange call mobile 13.0 1999 November
# 2 2 1999-11 1999-10-15 14:46 Play call mobile 23.0 1999 November
# 3 3 1999-11 1999-10-15 14:48 Plus call mobile 4.0 1999 November
# 4 4 1999-11 1999-10-15 17:27 T-Mobile call mobile 4.0 1999 November
# .. ... ... ... ... ... ... ... ... ...
# 825 825 2000-03 2000-03-13 00:38 AT&T sms international 1.0 2000 March
# 826 826 2000-03 2000-03-13 00:39 Orange sms mobile 1.0 2000 March
# 827 827 2000-03 2000-03-13 06:58 Orange data data 34.5 2000 March
# 828 828 2000-03 2000-03-14 00:13 AT&T sms international 1.0 2000 March
# 829 829 2000-03 2000-03-14 00:16 AT&T sms international 1.0 2000 March
# <BLANKLINE>
# [830 rows x 9 columns]
# %% Hints
# - `Series.str.split(expand=True)`
# - `df[ ['A', 'B'] ] = ...`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python has an is invalid version; expected: `3.9` or newer.'
>>> 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`.'
>>> pd.set_option('display.max_columns', 50)
>>> pd.set_option('display.max_rows', 200)
>>> pd.set_option('display.width', 500)
>>> pd.set_option('display.memory_usage', 'deep')
>>> pd.set_option('display.precision', 4)
>>> result # doctest: +NORMALIZE_WHITESPACE
id period datetime network item type duration year month
0 0 1999-11 1999-10-15 06:58 T-Mobile data data 34.5 1999 November
1 1 1999-11 1999-10-15 06:58 Orange call mobile 13.0 1999 November
2 2 1999-11 1999-10-15 14:46 Play call mobile 23.0 1999 November
3 3 1999-11 1999-10-15 14:48 Plus call mobile 4.0 1999 November
4 4 1999-11 1999-10-15 17:27 T-Mobile call mobile 4.0 1999 November
.. ... ... ... ... ... ... ... ... ...
825 825 2000-03 2000-03-13 00:38 AT&T sms international 1.0 2000 March
826 826 2000-03 2000-03-13 00:39 Orange sms mobile 1.0 2000 March
827 827 2000-03 2000-03-13 06:58 Orange data data 34.5 2000 March
828 828 2000-03 2000-03-14 00:13 AT&T sms international 1.0 2000 March
829 829 2000-03 2000-03-14 00:16 AT&T sms international 1.0 2000 March
<BLANKLINE>
[830 rows x 9 columns]
"""
# %% 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
# %% Types
result: pd.DataFrame
# %% Data
DATA = 'https://python3.info/_static/phones-pl.csv'
MONTHS = {
1: 'January',
2: 'February',
3: 'March',
4: 'April',
5: 'May',
6: 'June',
7: 'July',
8: 'August',
9: 'September',
10: 'October',
11: 'November',
12: 'December',
}
# %% Result
result = ...
# %% About
# - Name: DataFrame Mapping Substitute
# - Difficulty: medium
# - Lines: 10
# - Minutes: 8
# %% 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. Select `Polish` spreadsheet
# 3. Set header and index to data from file
# 4. Mind the encoding
# 5. Substitute Polish Diacritics to English alphabet letters
# 6. Compare `df.replace(regex=True)` with `df.apply()`
# 7. Run doctests - all must succeed
# %% Polish
# 1. Wczytaj dane z `DATA` jako `df: pd.DataFrame`
# 2. Wybierz arkusz `Polish`
# 3. Ustaw nagłówek i index na dane zaczytane z pliku
# 4. Zwróć uwagę na encoding
# 5. Podmień polskie znaki diakrytyczne na litery z alfabetu angielskiego
# 6. Porównaj `df.replace(regex=True)` z `df.apply()`
# 7. Uruchom doctesty - wszystkie muszą się powieść
# %% Expected
# >>> result
# Definicja Sprzet Oprogramowanie Kryteria wyjsciowe
# TRL
# 1 Zaobserwowanie i opisanie podstawowych zasad d... Zebrano wiedze naukowa dotyczaca podstawowych ... Zebrano wiedze naukowa dotyczaca podstawowych ... Zweryfikowane publikacja badania lezacych u po...
# 2 Sformulowanie koncepcji technologicznej lub pr... Stworzono innowacyjne rozwiazanie, zidentyfiko... Zidentyfikowano praktyczne zastosowanie, ale m... Udokumentowany opis aplikacji / koncepcji, kto...
# 3 Przeprowadzanie eksperymentalnie i analityczni... Badania analityczne pozwalaja na umieszczenie ... Opracowanie ograniczonej funkcjonalnosci do wa... Udokumentowane wyniki analityczne / eksperymen...
# 4 Przeprowadzenie weryfikacji komponentow techno... Stworzono niskiej wiernosci system lub jego ko... Kluczowe, funkcjonalne komponenty oprogramowan... Udokumentowane wyniki testow potwierdzajace zg...
# 5 Przeprowadzenie weryfikacji komponentow techno... Stworzono sredniej wiernosci system lub jego k... Zaimplementowane kompleksowe elementy oprogram... Udokumentowane wyniki testow potwierdzajace zg...
# 6 Dokonanie demonstracji technologii w srodowisk... Stworzono wysokiej wiernosci system lub jego k... Stworzona prototypowa implementacja oprogramow... Udokumentowane wyniki testow potwierdzajace zg...
# 7 Dokonanie demonstracji prototypu systemu w oto... Stworzono wysokiej wiernosci system lub jego k... Prototypowe oprogramowanie posiada wszystkie k... Udokumentowane wyniki testow potwierdzajace zg...
# 8 Zakonczenie badan i demonstracja ostatecznej f... Produkt koncowy w swojej ostatecznej konfigura... Cale oprogramowanie zostalo gruntownie sprawdz... Udokumentowane wyniki testow weryfikujacych pr...
# 9 Weryfikacja technologii w srodowisku operacyjn... Produkt koncowy jest z powodzeniem obslugiwany... Cale oprogramowanie zostalo gruntownie sprawdz... Udokumentowane wyniki operacyjne misji.
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python has an is invalid version; expected: `3.9` or newer.'
>>> 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`.'
>>> pd.set_option('display.max_columns', 50)
>>> pd.set_option('display.max_rows', 200)
>>> pd.set_option('display.width', 500)
>>> pd.set_option('display.memory_usage', 'deep')
>>> pd.set_option('display.precision', 4)
>>> result # doctest: +NORMALIZE_WHITESPACE
Definicja Sprzet Oprogramowanie Kryteria wyjsciowe
TRL
1 Zaobserwowanie i opisanie podstawowych zasad d... Zebrano wiedze naukowa dotyczaca podstawowych ... Zebrano wiedze naukowa dotyczaca podstawowych ... Zweryfikowane publikacja badania lezacych u po...
2 Sformulowanie koncepcji technologicznej lub pr... Stworzono innowacyjne rozwiazanie, zidentyfiko... Zidentyfikowano praktyczne zastosowanie, ale m... Udokumentowany opis aplikacji / koncepcji, kto...
3 Przeprowadzanie eksperymentalnie i analityczni... Badania analityczne pozwalaja na umieszczenie ... Opracowanie ograniczonej funkcjonalnosci do wa... Udokumentowane wyniki analityczne / eksperymen...
4 Przeprowadzenie weryfikacji komponentow techno... Stworzono niskiej wiernosci system lub jego ko... Kluczowe, funkcjonalne komponenty oprogramowan... Udokumentowane wyniki testow potwierdzajace zg...
5 Przeprowadzenie weryfikacji komponentow techno... Stworzono sredniej wiernosci system lub jego k... Zaimplementowane kompleksowe elementy oprogram... Udokumentowane wyniki testow potwierdzajace zg...
6 Dokonanie demonstracji technologii w srodowisk... Stworzono wysokiej wiernosci system lub jego k... Stworzona prototypowa implementacja oprogramow... Udokumentowane wyniki testow potwierdzajace zg...
7 Dokonanie demonstracji prototypu systemu w oto... Stworzono wysokiej wiernosci system lub jego k... Prototypowe oprogramowanie posiada wszystkie k... Udokumentowane wyniki testow potwierdzajace zg...
8 Zakonczenie badan i demonstracja ostatecznej f... Produkt koncowy w swojej ostatecznej konfigura... Cale oprogramowanie zostalo gruntownie sprawdz... Udokumentowane wyniki testow weryfikujacych pr...
9 Weryfikacja technologii w srodowisku operacyjn... Produkt koncowy jest z powodzeniem obslugiwany... Cale oprogramowanie zostalo gruntownie sprawdz... Udokumentowane wyniki operacyjne misji.
"""
# %% 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
# %% Types
result: pd.DataFrame
# %% Data
DATA = 'https://python3.info/_static/astro-trl.xlsx'
LETTERS_PLEN = {'ą': 'a', 'ć': 'c', 'ę': 'e',
'ł': 'l', 'ń': 'n', 'ó': 'o',
'ś': 's', 'ż': 'z', 'ź': 'z'}
# %% Result
result = ...
# %% About
# - Name: Pandas Read JSON OpenAPI
# - Difficulty: easy
# - Lines: 5
# - Minutes: 5
# %% 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. Use `requests` library
# 3. Transpose data
# 4. If cell is a `dict`, then extract value for `summary`
# 5. If cell is empty, leave `None`
# 6. Run doctests - all must succeed
# %% Polish
# 1. Wczytaj dane z `DATA` jako `df: pd.DataFrame`
# 2. Użyj biblioteki `requests`
# 3. Transponuj dane
# 4. Jeżeli komórka jest `dict`, to wyciągnij wartość dla `summary`
# 5. Jeżeli komórka jest pusta, pozostaw `None`
# 6. Uruchom doctesty - wszystkie muszą się powieść
# %% Expected
# >>> list(result.columns)
# ['put', 'post', 'get', 'delete']
#
# >>> list(result.index) # doctest: +NORMALIZE_WHITESPACE
# ['/pet', '/pet/findByStatus', '/pet/findByTags', '/pet/{petId}', '/pet/{petId}/uploadImage',
# '/store/inventory', '/store/order', '/store/order/{orderId}',
# '/user', '/user/createWithList', '/user/login', '/user/logout', '/user/{username}']
# %% Hints
# - `pandas.DataFrame()`
# - `DataFrame.map()`
# - `DataFrame.transpose()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python has an is invalid version; expected: `3.9` or newer.'
>>> 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`.'
>>> pd.set_option('display.max_columns', 50)
>>> pd.set_option('display.max_rows', 200)
>>> pd.set_option('display.width', 500)
>>> pd.set_option('display.memory_usage', 'deep')
>>> pd.set_option('display.precision', 4)
>>> list(result.columns)
['put', 'post', 'get', 'delete']
>>> list(result.index) # doctest: +NORMALIZE_WHITESPACE
['/pet', '/pet/findByStatus', '/pet/findByTags', '/pet/{petId}', '/pet/{petId}/uploadImage',
'/store/inventory', '/store/order', '/store/order/{orderId}',
'/user', '/user/createWithList', '/user/login', '/user/logout', '/user/{username}']
"""
# %% 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 requests
# %% Types
result: pd.DataFrame
# %% Data
DATA = 'https://python3.info/_static/openapi.json'
data = requests.get(DATA).json()['paths']
# %% Result
result = ...