Contenu du cours
Pandas: First Steps
Pandas: First Steps
1. Getting Started
Introduction to PandasSeriesTask: Coffee Orders SeriesTask: Barista's Favorites CoffeesAccessing Elements from a SeriesTask: Drink of the HourTask - Signature DrinksTask: Mid-Morning SpecialsTask - Fetching the Mid-Shift DrinksOperations over SeriesTask: Modifying a single elementTask: Modifying the Entire SeriesTask: Modifying Part of a SeriesTask: Processing the Restock of Inventory
2. Basics of Dataframes
What is a DataFrame?Task: Creating a Table of Popular Coffee DrinksTask: Tracking Coffee Bean DeliveriesTask: Weekly Coffee Sales ReportAdding new ColumnsTask: Finding Total Sales Per DrinkTask: Calculating Total Sales RevenueAdding new RowsTask: Adding a New Employee to the Café TeamTask: Adding New Coffee Types to the Café Menu
Accessing Elements from a Series
Default Indexing
We can access elements via their numerical (default) indices using the usual syntax series_name[index]
:
import pandas as pd temperatures = pd.Series( [22, 18, 25, 19] ) # Access the 3rd element print(temperatures[2])
If the Series has Custom Indices, then it's recommended to use the iloc
property for indexing:
import pandas as pd temperatures = pd.Series( [22, 18, 25, 19], index=["Monday", "Tuesday", "Wednesday", "Thursday"] ) # Accessing the 3rd element print(temperatures.iloc[2])
Custom Indexing
The syntax of Custom Indexing is very similar to accessing elements of a dictionary:
import pandas as pd temperatures = pd.Series( [22, 18, 25, 19], index=["Monday", "Tuesday", "Wednesday", "Thursday"] ) # Accessing the temperature on "Wednesday" print(temperatures["Wednesday"])
Slicing with Default Indices
We can slice a Series using the syntax:
python
It's important to note that the in case of default indices, the end
is exclusive, which can be better understood with the following example:
import pandas as pd temperatures = pd.Series( [22, 18, 25, 19, 21, 23, 20], index=["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] ) # The index "6" is excluded weekdays = temperatures.iloc[0:6] print(weekdays)
Slicing with Custom Indices
We can slice a series using it's custom indices too. In this case the syntax is the same as before, except the end
element is also included in the slice:
import pandas as pd temperatures = pd.Series( [22, 18, 25, 19, 21, 23, 20], index=["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] ) # "Friday" is included in the slice weekdays = temperatures['Monday':'Friday'] print(weekdays)
1. What will be the output of the following code?
2. Which method is recommended to access elements by position when using custom indices?
3. What is the output of this code?
Tout était clair ?
Merci pour vos commentaires !
Section 1. Chapitre 5