Last updated
Selecting Rows
Definition: Pandas has two row selectors: iloc selects by position (like a list index), and loc selects by label or by a condition.
Example 1 — by position with iloc
import pandas as pd
df = pd.DataFrame({
"name": ["Sam", "Alex", "Jo"],
"age": [25, 30, 22]
})
print(df.iloc[0]) # first row
print(df.iloc[1]["name"])# value in row 1, column name
Example 2 — by label with loc
import pandas as pd
df = pd.DataFrame({"name": ["Sam", "Alex", "Jo"], "age": [25, 30, 22]})
print(df.loc[0, "name"]) # row label 0, column name
Example 3 — a range of rows
import pandas as pd
df = pd.DataFrame({"name": ["Sam","Alex","Jo","Pat"], "age": [25,30,22,40]})
print(df.iloc[0:2]) # first two rows
💡 Tip: remember "iloc = integer position" and "loc = label". Mixing them up is the most common Pandas beginner slip.
Try it Yourself
Output
Ad · responsive