data manipulation
row slicing
column slicing
data analysis
programming techniques

What is row slicing vs What is column slicing?

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

Row slicing selects a subset of rows from a dataset while keeping all columns. Column slicing selects a subset of columns while keeping all rows. In NumPy, row slicing uses array[start:stop] and column slicing uses array[:, start:stop]. In pandas, iloc and loc handle both by position or label. Understanding the difference is essential for data filtering, feature selection, and preparing datasets for machine learning models.

NumPy Row Slicing

python
1import numpy as np
2
3data = np.array([
4    [10, 20, 30],
5    [40, 50, 60],
6    [70, 80, 90],
7    [100, 110, 120],
8])
9
10# Row slicing — select rows 1 and 2
11rows = data[1:3]
12print(rows)
13# [[40 50 60]
14#  [70 80 90]]
15
16# First two rows
17print(data[:2])
18# [[10 20 30]
19#  [40 50 60]]
20
21# Every other row
22print(data[::2])
23# [[ 10  20  30]
24#  [ 70  80  90]]
25
26# Specific rows by index array
27print(data[[0, 2, 3]])
28# [[ 10  20  30]
29#  [ 70  80  90]
30#  [100 110 120]]

Row slicing operates on the first axis (axis 0). The syntax array[start:stop:step] selects rows by position.

NumPy Column Slicing

python
1import numpy as np
2
3data = np.array([
4    [10, 20, 30, 40],
5    [50, 60, 70, 80],
6    [90, 100, 110, 120],
7])
8
9# Column slicing — select columns 1 and 2
10cols = data[:, 1:3]
11print(cols)
12# [[ 20  30]
13#  [ 60  70]
14#  [100 110]]
15
16# First column only
17print(data[:, 0])
18# [10 50 90]  — returns 1D array
19
20# Keep as 2D column vector
21print(data[:, 0:1])
22# [[ 10]
23#  [ 50]
24#  [ 90]]
25
26# Specific columns by index array
27print(data[:, [0, 3]])
28# [[ 10  40]
29#  [ 50  80]
30#  [ 90 120]]

Column slicing uses : for "all rows" followed by the column index. array[:, n] returns a 1D array, while array[:, n:n+1] preserves the 2D shape.

Pandas Row Slicing

python
1import pandas as pd
2
3df = pd.DataFrame({
4    'name': ['Alice', 'Bob', 'Charlie', 'Diana'],
5    'age': [25, 30, 35, 28],
6    'salary': [70000, 80000, 90000, 75000],
7    'city': ['NYC', 'LA', 'Chicago', 'NYC'],
8})
9
10# By position (iloc)
11print(df.iloc[1:3])
12#      name  age  salary     city
13# 1     Bob   30   80000       LA
14# 2  Charlie   35   90000  Chicago
15
16# By label (loc)
17print(df.loc[0:2])  # Inclusive on both ends with loc
18#      name  age  salary     city
19# 0   Alice   25   70000      NYC
20# 1     Bob   30   80000       LA
21# 2  Charlie   35   90000  Chicago
22
23# Boolean row slicing (filtering)
24nyc_people = df[df['city'] == 'NYC']
25print(nyc_people)
26#    name  age  salary city
27# 0  Alice   25   70000  NYC
28# 3  Diana   28   75000  NYC

iloc uses zero-based integer positions (exclusive end). loc uses index labels (inclusive end). Boolean indexing is the most common form of row slicing for data filtering.

Pandas Column Slicing

python
1import pandas as pd
2
3df = pd.DataFrame({
4    'name': ['Alice', 'Bob', 'Charlie'],
5    'age': [25, 30, 35],
6    'salary': [70000, 80000, 90000],
7    'city': ['NYC', 'LA', 'Chicago'],
8})
9
10# By column name (most common)
11print(df[['name', 'salary']])
12#      name  salary
13# 0   Alice   70000
14# 1     Bob   80000
15# 2  Charlie   90000
16
17# By position with iloc
18print(df.iloc[:, 1:3])  # Columns 1 and 2
19#    age  salary
20# 0   25   70000
21# 1   30   80000
22# 2   35   90000
23
24# By label range with loc
25print(df.loc[:, 'age':'city'])  # Inclusive range
26#    age  salary     city
27# 0   25   70000      NYC
28# 1   30   80000       LA
29# 2   35   90000  Chicago
30
31# Drop columns (inverse of column slicing)
32print(df.drop(columns=['city']))

Selecting columns by name (df[['col1', 'col2']]) is the standard pandas pattern. iloc[:, start:stop] selects by position when names are unknown.

Combined Row and Column Slicing

python
1import pandas as pd
2
3df = pd.DataFrame({
4    'name': ['Alice', 'Bob', 'Charlie', 'Diana'],
5    'age': [25, 30, 35, 28],
6    'salary': [70000, 80000, 90000, 75000],
7})
8
9# Rows 0-1, columns 'name' and 'age'
10print(df.loc[0:1, ['name', 'age']])
11#    name  age
12# 0  Alice   25
13# 1   Bob   30
14
15# Rows 1-2, columns 1-2 by position
16print(df.iloc[1:3, 1:3])
17#    age  salary
18# 1   30   80000
19# 2   35   90000
20
21# Boolean rows + specific columns
22young = df.loc[df['age'] < 30, ['name', 'salary']]
23print(young)
24#    name  salary
25# 0  Alice   70000
26# 3  Diana   75000

Common Pitfalls

  • Confusing iloc and loc ranges: iloc[1:3] is exclusive (rows 1, 2). loc[1:3] is inclusive (rows 1, 2, 3). Mixing them up causes off-by-one errors.
  • Single column returns Series, not DataFrame: df['age'] returns a Series. df[['age']] (double brackets) returns a DataFrame. This matters for downstream operations expecting 2D input.
  • NumPy slices are views, not copies: slice = array[1:3] is a view — modifying slice modifies the original array. Use .copy() if you need an independent copy.
  • Chained indexing warning in pandas: df[df['age'] > 25]['salary'] = 0 triggers SettingWithCopyWarning and may not modify the original DataFrame. Use df.loc[df['age'] > 25, 'salary'] = 0 instead.
  • Column order assumptions in NumPy: NumPy arrays do not have column names. Slicing array[:, 2] assumes you know which feature is in column 2. Use pandas DataFrames for named column access.

Summary

  • Row slicing selects rows: array[1:3] (NumPy), df.iloc[1:3] or df.loc[1:3] (pandas)
  • Column slicing selects columns: array[:, 1:3] (NumPy), df[['col1', 'col2']] (pandas)
  • iloc is position-based (exclusive end), loc is label-based (inclusive end)
  • Boolean indexing (df[df['col'] > value]) is the most common row slicing pattern
  • NumPy slices are views (modify original), pandas slices depend on context
  • Use df.loc[rows, columns] for combined row and column selection

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.