How to Select Rows and Columns in Pandas: loc and iloc
Selecting the right rows and columns is one of the most important skills in Pandas. A DataFrame may contain thousands of records and many variables, but most analysis starts by retrieving only the fields and observations needed for a question. This tutorial explains how to select Pandas columns, select rows by label with .loc, select by integer position with .iloc, and combine selection with conditions using clear, practical examples.
This page focuses on selecting existing data. If you need an introduction to table structure, see the Pandas DataFrame tutorial; to build a new table, read how to create a Pandas DataFrame.
- Create a sample DataFrame
- Select one or more columns
- Select rows and columns with loc
- Select by position with iloc
- Select ranges of rows and columns
- Select rows using conditions
- Combine multiple conditions
- Select a single value with at and iat
- Series versus DataFrame results
- Common selection mistakes
- Practice exercises
- Frequently asked questions
1. Create a Sample Pandas DataFrame
We will use the same small employee dataset throughout the examples. Run this code first in a Python script or Jupyter Notebook. It creates the DataFrame and assigns employee IDs as index labels.
import pandas as pd
employees = pd.DataFrame({
"Name": ["Amina", "Bilal", "Chen", "Dina", "Ethan"],
"Department": ["IT", "Sales", "IT", "HR", "Sales"],
"Age": [28, 35, 31, 26, 42],
"Salary": [72000, 65000, 81000, 59000, 88000],
"City": ["London", "Leeds", "London", "Bristol", "Leeds"]
}, index=["E101", "E102", "E103", "E104", "E105"])
print(employees)
Name Department Age Salary City E101 Amina IT 28 72000 London E102 Bilal Sales 35 65000 Leeds E103 Chen IT 31 81000 London E104 Dina HR 26 59000 Bristol E105 Ethan Sales 42 88000 Leeds
The index labels are employee IDs, while the column labels are Name, Department, Age, Salary and City. This example makes an important distinction: labels identify data by name; positions identify where data appears in the current order.
2. Select Columns in Pandas
Select a single column
Put a column label inside square brackets to select one column. A single column selection normally returns a Pandas Series.
names = employees["Name"]
print(names)
print(type(names))
Select multiple columns
Pass a list of column names inside the outer square brackets to select multiple columns. The result is a DataFrame.
name_salary = employees[["Name", "Salary"]]
print(name_salary)
Column order in the result follows the order of the names in your selection list. This is useful when preparing a smaller table for a report or later calculation.
Select a column using dot notation
For some simple column names, dot notation also works, such as employees.Name. However, bracket notation—employees["Name"]—is generally safer and more consistent. Dot notation does not work for names containing spaces or punctuation and can conflict with DataFrame attributes or methods.
3. Select Rows and Columns with loc
.loc selects data by index labels and column labels. Its general form is:
df.loc[row_label, column_label]
You can provide one label, a list of labels, a slice of labels or a Boolean condition. The comma separates the row selection from the column selection.
Select one row by its index label
print(employees.loc["E103"])
Selecting one row this way returns a Series, with column names as the Series index.
Select specific rows
print(employees.loc[["E101", "E104"]])
Select specific rows and columns
print(employees.loc[["E101", "E103"], ["Name", "Salary"]])
Select all rows but only selected columns
print(employees.loc[:, ["Department", "Salary"]])
The colon (:) means “all labels” along that axis. In employees.loc[:, ["Department", "Salary"]], all rows are included, but only the two named columns are returned.
Slice index labels with loc
print(employees.loc["E102":"E104", ["Name", "Department"]])
.loc include the stop label when that label exists. This differs from normal Python list slicing and from positional slicing with .iloc.4. Select Rows and Columns by Position with iloc
.iloc selects by zero-based integer position rather than index labels. Its general form is df.iloc[row_position, column_position]. The first row and first column are at position 0.
Select the first row
print(employees.iloc[0])
Select the third row
print(employees.iloc[2])
Select rows and columns by position
print(employees.iloc[0:3, 0:2])
This returns the first three rows and the first two columns. Positional slices exclude the stop position, so 0:3 means positions 0, 1 and 2.
Select non-adjacent rows and columns
print(employees.iloc[[0, 3, 4], [0, 3]])
This selects rows at positions 0, 3 and 4, and columns at positions 0 and 3. Use integer positions only when the current order is the one you intend to rely on.
5. Select Ranges of Rows and Columns
Both .loc and .iloc can select a range, but their slice boundaries differ.
| Expression | Selection method | How the stop works |
|---|---|---|
df.loc["E101":"E103"] | Index labels | Includes E103 if it exists in the index. |
df.iloc[0:3] | Integer positions | Includes positions 0, 1 and 2; excludes position 3. |
df.iloc[:, 1:4] | Column positions | Includes columns at positions 1, 2 and 3. |
Examples:
first_two_rows = employees.iloc[:2]
last_two_rows = employees.iloc[-2:]
all_rows_two_columns = employees.iloc[:, :2]
print(first_two_rows)
print(last_two_rows)
print(all_rows_two_columns)
Negative positions count from the end. For example, -1 refers to the last row or column position.
6. Select Rows Using Conditions
Boolean filtering creates a condition for each row and returns the rows where the condition is true. This is often called Boolean indexing. It is useful when you want records that match a business rule, such as employees in one department or people above a salary threshold.
Filter by one condition
it_staff = employees[employees["Department"] == "IT"]
print(it_staff)
The expression inside the outer brackets produces a Boolean Series. Pandas uses it to keep rows where the condition is true.
Filter and return only selected columns
it_names = employees.loc[employees["Department"] == "IT", ["Name", "City"]]
print(it_names)
Use comparison operators
high_salary = employees[employees["Salary"] >= 75000]
print(high_salary[["Name", "Salary"]])
Common operators include == (equal), != (not equal), > (greater than), >= (greater than or equal), < (less than) and <= (less than or equal).
7. Combine Multiple Conditions
Use parentheses around each condition and combine them with Pandas' element-wise logical operators:
&means AND: both conditions must be true.|means OR: at least one condition must be true.~means NOT: reverse a Boolean condition.
AND: both conditions must match
result = employees[(employees["Department"] == "IT") & (employees["Salary"] > 75000)]
print(result)
OR: either condition can match
result = employees[(employees["City"] == "Leeds") | (employees["Department"] == "HR")]
print(result)
NOT: exclude a category
not_sales = employees[~(employees["Department"] == "Sales")]
print(not_sales)
and or or to combine whole-column conditions. Use & and |, and put parentheses around each comparison.For more filtering examples, continue to the dedicated Pandas DataFrame filtering tutorial.
8. Select a Single Value with at and iat
When you need one cell, .at uses row and column labels, while .iat uses integer positions. They are convenient for scalar lookups.
print(employees.at["E103", "Salary"]) # Label-based lookup
print(employees.iat[2, 3]) # Position-based lookup
In this example, both expressions return the salary for the third employee. Use .at when you know the labels and .iat when you know the positions.
9. Does Selection Return a Series or DataFrame?
The type of object returned depends on how you select the data. This distinction matters because later code may expect either a one-dimensional Series or a two-dimensional DataFrame.
| Code | Typical result |
|---|---|
employees["Name"] | Series |
employees[["Name"]] | One-column DataFrame |
employees.loc["E101"] | Series representing one row |
employees.loc[["E101"]] | One-row DataFrame |
employees.iloc[0, 0] | Single cell value |
employees.iloc[[0], [0]] | One-cell DataFrame |
If you are unsure, check the returned object's type using type(...) or its dimensions using .shape.
10. Common Pandas Selection Mistakes
Using a column name that does not exist
A misspelling, extra space or difference in capitalisation can cause a KeyError. Inspect df.columns to see the actual labels.
Confusing labels with positions
.loc[0] looks for the index label 0; .iloc[0] selects the first row position. They are not interchangeable when the index uses custom labels.
Forgetting parentheses around conditions
When using & or |, wrap each comparison in parentheses to avoid operator-precedence errors.
Expecting loc and iloc slices to behave the same
Label-based .loc slices include the end label, while positional .iloc slices exclude the stop position.
Changing the DataFrame unintentionally
Selection normally returns the requested data; if you want to make an independent working copy for subsequent edits, use .copy(), for example subset = employees.loc[employees["Department"] == "IT"].copy().
11. Practice Exercises
Try these questions using the employees DataFrame created at the start of the tutorial. Attempt each one before checking the solution.
- Select only the
Namecolumn. - Select the
NameandCitycolumns for employees E102 and E105. - Use
.ilocto return the first two rows. - Find employees whose salary is at least 70,000.
- Find employees who work in IT and are older than 29.
- Return the salary for employee E104 using
.at.
Show solutions
employees["Name"]
employees.loc[["E102", "E105"], ["Name", "City"]]
employees.iloc[:2]
employees[employees["Salary"] >= 70000]
employees[(employees["Department"] == "IT") & (employees["Age"] > 29)]
employees.at["E104", "Salary"]
12. Frequently Asked Questions
How do I select a column in Pandas?
Use df["column_name"] to select one column as a Series. Use df[["column_a", "column_b"]] to select multiple columns as a DataFrame.
What is the difference between loc and iloc in Pandas?
.loc selects by row and column labels, while .iloc selects by integer positions. The methods also differ in slice behaviour: .loc includes the stop label, while .iloc excludes the stop position.
How do I select a row by its index in Pandas?
Use df.loc[index_label]. To keep the result as a DataFrame, put the label in a list, such as df.loc[[index_label]].
How do I select the first row in Pandas?
Use df.iloc[0] to select the first row by position. Alternatively, df.head(1) returns the first row as a one-row DataFrame.
How do I select rows based on a condition?
Use Boolean indexing, for example df[df["Age"] > 30]. For multiple conditions, use parenthesised comparisons combined with & or |.
Why does loc raise a KeyError?
A KeyError usually means the requested row or column label is not present. Check the exact index labels or column names, including spaces and capitalisation.
Continue Learning Pandas
Once you can select rows and columns, continue with these related lessons:
