Lesson 04
Getting and Setting Series Values
Read Series values by label with loc and by position with iloc, slice both ways, pass lists of labels, and assign new values back.
A Series has two ways to reach a value: the label and the position. loc always means the label and iloc always means the position. Being explicit avoids the classic confusion when the labels are themselves numbers.
By label and by position
loc takes a label and raises KeyError when it is missing. iloc takes a position, counts from 0, accepts negatives, and raises IndexError when it runs past the end.
import pandas as pd
names = pd.Series(["Avery", "Jordan", "Casey", "Riley", "Morgan"],
index=["a", "b", "c", "d", "e"])
print(names.loc["d"])
print(names.iloc[0], names.iloc[-1])
try:
names.loc["k"]
except KeyError as error:
print("KeyError:", error)Output:
Riley
Avery Morgan
KeyError: 'k'Slices differ at the end
A position slice leaves the stop out, exactly like a list. A label slice keeps the stop label in, because pandas cannot know what comes after it. This is the one difference people trip over.
import pandas as pd
names = pd.Series(["Avery", "Jordan", "Casey", "Riley", "Morgan"],
index=["a", "b", "c", "d", "e"])
print(names.iloc[1:4])
print(names.loc["b":"e"])Output:
b Jordan
c Casey
d Riley
dtype: object
b Jordan
c Casey
d Riley
e Morgan
dtype: objectSeveral values at once
Pass a list of labels to loc, or a list of positions to iloc. The result is a new Series in the order you asked for, and a label may repeat.
import pandas as pd
names = pd.Series(["Avery", "Jordan", "Casey", "Riley", "Morgan"],
index=["a", "b", "c", "d", "e"])
print(names.loc[["d", "e", "a"]])
print(names.iloc[[2, 3, 0]])Output:
d Riley
e Morgan
a Avery
dtype: object
c Casey
d Riley
a Avery
dtype: objectChange values
The same accessors work on the left of =. Assign one value, or assign to a slice or a list of labels to set several at once. A Series is mutable, so this changes it in place.
import pandas as pd
names = pd.Series(["Avery", "Jordan", "Casey", "Riley", "Morgan"],
index=["a", "b", "c", "d", "e"])
names.iloc[2] = "Quinn"
names.loc["e"] = "Harper"
names.loc["a":"c"] = "unassigned"
print(names)Output:
a unassigned
b unassigned
c unassigned
d Riley
e Harper
dtype: objectAdd a label
Assigning to a label that does not exist appends it. That is the difference between a Series and a Python list, where an unknown position is an error.
import pandas as pd
scores = pd.Series({"Avery": 88, "Jordan": 74})
scores.loc["Casey"] = 91
print(scores)
print(scores.get("Riley", "not found"))Output:
Avery 88
Jordan 74
Casey 91
dtype: int64
not foundKey takeaways
-
locis labels,ilocis positions -
iloc[1:4]leaves the stop out.loc['b':'e']keeps it in -
A list inside either one returns several values, in your order
-
Assigning to a new label appends it
-
Next: Series Statistics
-
Previous: Series Attributes
Loading playground…
Check your understanding
Getting and Setting Series Values Quiz
What does loc use?
1 / 10