Python tutoring online
Home

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.

Learn Pandas with Practical Guidance

If you need help with Python, Pandas, data analysis coursework or a project, one-to-one tutoring can help you practise selecting, cleaning and analysing real datasets.

Get 1-on-1 Python Tutoring

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.

Python
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.

Python
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.

Python
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

Python
print(employees.loc["E103"])

Selecting one row this way returns a Series, with column names as the Series index.

Select specific rows

Python
print(employees.loc[["E101", "E104"]])

Select specific rows and columns

Python
print(employees.loc[["E101", "E103"], ["Name", "Salary"]])

Select all rows but only selected columns

Python
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

Python
print(employees.loc["E102":"E104", ["Name", "Department"]])
Important: label-based slices with .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

Python
print(employees.iloc[0])

Select the third row

Python
print(employees.iloc[2])

Select rows and columns by position

Python
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

Python
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.

ExpressionSelection methodHow the stop works
df.loc["E101":"E103"]Index labelsIncludes E103 if it exists in the index.
df.iloc[0:3]Integer positionsIncludes positions 0, 1 and 2; excludes position 3.
df.iloc[:, 1:4]Column positionsIncludes columns at positions 1, 2 and 3.

Examples:

Python
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

Python
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

Python
it_names = employees.loc[employees["Department"] == "IT", ["Name", "City"]]
print(it_names)

Use comparison operators

Python
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:

AND: both conditions must match

Python
result = employees[(employees["Department"] == "IT") & (employees["Salary"] > 75000)]
print(result)

OR: either condition can match

Python
result = employees[(employees["City"] == "Leeds") | (employees["Department"] == "HR")]
print(result)

NOT: exclude a category

Python
not_sales = employees[~(employees["Department"] == "Sales")]
print(not_sales)
Common mistake: do not use Python's 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.

Python
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.

CodeTypical 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.

  1. Select only the Name column.
  2. Select the Name and City columns for employees E102 and E105.
  3. Use .iloc to return the first two rows.
  4. Find employees whose salary is at least 70,000.
  5. Find employees who work in IT and are older than 29.
  6. Return the salary for employee E104 using .at.
Show solutions
Python
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:

Need Help with Pandas or Data Analysis?

Get support with DataFrames, filtering, data cleaning, Python programming or a data-analysis assignment through one-to-one online tutoring.

Explore Python Tutoring



Stuck Learning Python?

Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.

Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.

    Get Python Tutoring

PythonTutor.net

Home    Tutorial     Online Live Trainings    Contact Us           © 2026 All rights reserved by www.PythonTutor.net