Item assignment with .loc and .iloc
The pandas library is optimized for reading, exploring, and evaluating data. Operations that try to mutate or change data are far less efficient.
However, when you must mutate your data, you can use .loc
and .iloc
to do it.
How to do it
Let’s start with a very small pd.Series
:
ser = pd.Series(range(3), index=list("abc"))
pd.Series.loc
is useful when you want to assign a value by matching against the label of an index. For example, if we wanted to store the value 42
where our row index contained a value of "b"
, we would write:
ser.loc["b"] = 42
ser
a 0
b 42
c 2
dtype: int64
pd.Series.iloc
is used when you want to assign a value positionally. To assign the value -42
to the second element in our pd.Series
, we would write:
ser.iloc[2] = -42
ser
a 0
b 42
c -42
dtype: int64
There’s more…
The cost of mutating data through pandas can...