0
0
NumPydata~5 mins

Slicing rows and columns in NumPy

Choose your learning style9 modes available
Introduction

Slicing helps you pick specific rows and columns from a table of data. It makes it easy to focus on the parts you want.

You want to look at the first 5 rows of a dataset to understand it.
You need to select a few columns like age and salary from a big table.
You want to get rows 10 to 20 to analyze a smaller group.
You want to skip some rows or columns to clean data.
You want to create a smaller table from a big one for faster work.
Syntax
NumPy
array[row_start:row_end, col_start:col_end]

Rows and columns start counting at 0.

The end index is not included in the slice.

Examples
Selects rows 0, 1, 2 and columns 1, 2, 3.
NumPy
data[0:3, 1:4]
Selects all rows in column 2.
NumPy
data[:, 2]
Selects rows 5 to 9 and all columns.
NumPy
data[5:10, :]
Selects last 3 rows and last 2 columns.
NumPy
data[-3:, -2:]
Sample Program

This code shows how to slice rows and columns from a 2D numpy array. It prints the original array and three slices.

NumPy
import numpy as np

# Create a 5x5 array with numbers 0 to 24
 data = np.arange(25).reshape(5,5)

# Select rows 1 to 3 and columns 2 to 4
slice1 = data[1:4, 2:5]

# Select all rows in column 0
slice2 = data[:, 0]

# Select last 2 rows and last 3 columns
slice3 = data[-2:, -3:]

print("Original array:\n", data)
print("\nSlice rows 1-3, cols 2-4:\n", slice1)
print("\nAll rows, column 0:\n", slice2)
print("\nLast 2 rows, last 3 columns:\n", slice3)
OutputSuccess
Important Notes

Remember that slicing does not copy data, it creates a view. Changing the slice changes the original array.

You can use negative numbers to count from the end.

Summary

Slicing lets you pick parts of rows and columns easily.

Use start:end to choose ranges; end is not included.

Use ':' to select all rows or columns.