What is row slicing vs What is column slicing?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
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
Row slicing operates on the first axis (axis 0). The syntax array[start:stop:step] selects rows by position.
NumPy Column Slicing
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
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
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
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 — modifyingslicemodifies the original array. Use.copy()if you need an independent copy. - Chained indexing warning in pandas:
df[df['age'] > 25]['salary'] = 0triggersSettingWithCopyWarningand may not modify the original DataFrame. Usedf.loc[df['age'] > 25, 'salary'] = 0instead. - 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]ordf.loc[1:3](pandas) - Column slicing selects columns:
array[:, 1:3](NumPy),df[['col1', 'col2']](pandas) ilocis position-based (exclusive end),locis 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

