Given:
test = np.array([[1, 2], [3, 4], [5, 6]])
test[i]
gives the ith row (e.g. [1, 2]
). How do I access the ith column? (e.g. [1, 3, 5]
). Also, would this be an expensive operation?
Answers
To access the ith column of a NumPy array, you can use slicing. In your example:
import numpy as np
test = np.array([[1, 2], [3, 4], [5, 6]])
To access the ith
column, you can do:
column_i = test[:, i] # Replace i with the index of the column you want
For example, if you want to access the first column (i = 0
):
column_0 = test[:, 0]
print(column_0) # Output: [1 3 5]
Explanation:
test[:, i]
means:- The
:
selects all rows. - The
i
selects thei
th column.
- The
Performance:
This is not an expensive operation in NumPy because it is essentially a view (a reference) on the original data, not a deep copy. NumPy's slicing operations are very efficient and done in constant time (O(1)
), so there is no significant overhead for accessing columns.
If you modify the column_i
array (using in-place operations), it will modify the original test
array as well since they share the same memory. If you want a copy instead of a view, you can explicitly copy the column like this:
column_0_copy = test[:, 0].copy()