0
0
NumpyHow-ToBeginner ยท 3 min read

How to Select Columns in NumPy Arrays Easily

To select columns in a numpy array, use slicing with array[:, column_index] where : means all rows and column_index is the column number. You can select multiple columns using a list of indices like array[:, [0, 2]].
๐Ÿ“

Syntax

Use array[:, column_index] to select one column, where : means all rows and column_index is the column number. To select multiple columns, use array[:, [col1, col2, ...]] with a list of column indices.

python
array[:, column_index]
array[:, [col1, col2, ...]]
๐Ÿ’ป

Example

This example shows how to select a single column and multiple columns from a 2D NumPy array.

python
import numpy as np

# Create a 3x4 array
arr = np.array([[10, 20, 30, 40],
                [50, 60, 70, 80],
                [90, 100, 110, 120]])

# Select the second column (index 1)
col_1 = arr[:, 1]

# Select the first and third columns (indices 0 and 2)
cols_0_2 = arr[:, [0, 2]]

print("Original array:\n", arr)
print("\nSecond column:\n", col_1)
print("\nFirst and third columns:\n", cols_0_2)
Output
Original array: [[ 10 20 30 40] [ 50 60 70 80] [ 90 100 110 120]] Second column: [ 20 60 100] First and third columns: [[ 10 30] [ 50 70] [ 90 110]]
โš ๏ธ

Common Pitfalls

One common mistake is forgetting to use : for rows, which leads to errors or wrong shapes. For example, array[1] selects a row, not a column. Also, using a single index without a list returns a 1D array, while using a list returns a 2D array.

python
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])

# Wrong: tries to select column without rows slice
# This returns a row, not a column
wrong = arr[1]

# Right: select second column
right = arr[:, 1]

# Wrong: single index returns 1D array
single_col = arr[:, 1]

# Right: list of indices returns 2D array
multi_cols = arr[:, [0, 2]]

print("Wrong (row):", wrong)
print("Right (column):", right)
print("Single column shape:", single_col.shape)
print("Multiple columns shape:", multi_cols.shape)
Output
Wrong (row): [4 5 6] Right (column): [2 5] Single column shape: (2,) Multiple columns shape: (2, 2)
๐Ÿ“Š

Quick Reference

OperationSyntaxDescription
Select one columnarray[:, col_index]Selects all rows for one column
Select multiple columnsarray[:, [col1, col2]]Selects all rows for listed columns
Select a rowarray[row_index, :]Selects all columns for one row
Select subarrayarray[row_start:row_end, col_start:col_end]Selects a block of rows and columns
โœ…

Key Takeaways

Use array[:, column_index] to select a single column from all rows.
Use array[:, [col1, col2]] to select multiple columns at once.
Remember that array[row_index] selects a row, not a column.
Selecting a single column returns a 1D array; selecting multiple columns returns a 2D array.
Always include the row slice ':' to select columns properly.