Mixing position-based and label-based selection
Since pd.DataFrame.iloc
is used for position-based selection and pd.DataFrame.loc
is for label-based selection, users must take an extra step if attempting to select by label in one dimension and by position in another. As mentioned in previous sections, the majority of pd.DataFrame
objects constructed will place heavy significance on the labels used for the columns, with little care for how those columns are ordered. The inverse is true for the rows, so being able to effectively mix and match both styles is of immense value.
How to do it
Let’s start with a pd.DataFrame
that uses the default auto-numbered pd.RangeIndex
in the rows but has custom string labels for the columns:
df = pd.DataFrame([
[24, 180, "blue"],
[42, 166, "brown"],
[22, 160, "green"],
], columns=["age", "height_cm", "eye_color"])
df
age height_cm eye_color
0 ...