Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Accessing Elements from a Series | Getting Started
Pandas: First Steps
course content

Contenu du cours

Pandas: First Steps

Pandas: First Steps

1. Getting Started
2. Basics of Dataframes

book
Accessing Elements from a Series

Default Indexing

We can access elements via their numerical (default) indices using the usual syntax series_name[index]:

12345678
import pandas as pd temperatures = pd.Series( [22, 18, 25, 19] ) # Access the 3rd element print(temperatures[2])
copy

If the Series has Custom Indices, then it's recommended to use the iloc property for indexing:

123456789
import pandas as pd temperatures = pd.Series( [22, 18, 25, 19], index=["Monday", "Tuesday", "Wednesday", "Thursday"] ) # Accessing the 3rd element print(temperatures.iloc[2])
copy

Custom Indexing

The syntax of Custom Indexing is very similar to accessing elements of a dictionary:

123456789
import pandas as pd temperatures = pd.Series( [22, 18, 25, 19], index=["Monday", "Tuesday", "Wednesday", "Thursday"] ) # Accessing the temperature on "Wednesday" print(temperatures["Wednesday"])
copy

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:

1234567891011
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)
copy

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:

1234567891011
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)
copy

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?

question mark

What will be the output of the following code?

Select the correct answer

question mark

Which method is recommended to access elements by position when using custom indices?

Select the correct answer

question mark

What is the output of this code?

Select the correct answer

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 1. Chapitre 5
Nous sommes désolés de vous informer que quelque chose s'est mal passé. Qu'est-il arrivé ?
some-alt