Python – Iterate over Columns in NumPy
Last Updated :
26 Feb, 2023
Numpy (abbreviation for ‘Numerical Python‘) is a library for performing large-scale mathematical operations in a fast and efficient manner. This article serves to educate you about methods one could use to iterate over columns in an 2D NumPy array. Since a single-dimensional array only consists of linear elements, there doesn’t exists a distinguished definition of rows and columns in them. Therefore, in order to perform such operations we need an array whose len(ary.shape) > 1 . To install NumPy on your python environment, type the following code in your OS’s Command Processor (CMD, Bash etc):
pip install numpy
We would be taking a look at several methods of iterating over a column of an Array/Matrix:-
METHOD 1: CODE: Use of primitive 2D Slicing operation on an array to get the desired column/columns
Python3
import numpy as np
ary = np.arange( 1 , 25 , 1 )
ary = ary.reshape( 5 , 5 )
print (ary)
for col in range (ary.shape[ 1 ]):
print (ary[:, col])
|
Output:
[[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
[ 0 5 10 15 20]
[ 1 6 11 16 21]
[ 2 7 12 17 22]
[ 3 8 13 18 23]
[ 4 9 14 19 24]
Time complexity: O(n^2) where n is the size of the array.
Auxiliary space: O(n) as only one new array is created during the reshaping operation.
Explanation: In the above code, we firstly create an linear array of 25 elements (0-24) using np.arange(25). Then we reshape (transform 1D to 2D) using np.reshape() to create a 2D array out of a linear array. Then we output the transformed array. Now we used a for loop which would iterate x times (where x is the number of columns in the array) for which we used range() with the argument ary.shape[1] (where shape[1] = number of columns in a 2D symmetric array). In each iteration we output a column out of the array using ary[:, col] which means that give all elements of the column number = col.
METHOD 2: In this method we would transpose the array to treat each column element as a row element (which in turn is equivalent of column iteration).
Code:
Python3
import numpy as np
ary = np.array([[ 0 , 1 , 2 , 3 , 4 ],
[ 5 , 6 , 7 , 8 , 9 ],
[ 10 , 11 , 12 , 13 , 14 ],
[ 15 , 16 , 17 , 18 , 19 ],
[ 20 , 21 , 22 , 23 , 24 ]])
for col in ary.T:
print (col)
|
Output:
[ 0 5 10 15 20]
[ 1 6 11 16 21]
[ 2 7 12 17 22]
[ 3 8 13 18 23]
[ 4 9 14 19 24]
Time complexity: O(n*m)
Auxiliary space: O(m)
Explanation: Firstly, we created an 2D array (same as the previous example) using np.array() and initialized it with 25 values. Then we transposed the array, using ary.T which in turn switches the rows with the columns and columns with the rows. Then we iterated over each row of this transposed array and printed the row values.
Similar Reads
Iterate over a list in Python
Python provides several ways to iterate over list. The simplest and the most common way to iterate over a list is to use a for loop. This method allows us to access each element in the list directly. Example: Print all elements in the list one by one using for loop. [GFGTABS] Python a = [1, 3, 5, 7,
3 min read
numpy.ones_like() in Python
The numpy.one_like() function returns an array of given shape and type as a given array, with ones. Syntax: numpy.ones_like(array, dtype = None, order = 'K', subok = True) Parameters : array : array_like input subok : [optional, boolean]If true, then newly created array will be sub-class of array; o
2 min read
numpy.apply_over_axes() in Python
The numpy.apply_over_axes()applies a function repeatedly over multiple axes in an array. Syntax : numpy.apply_over_axes(func, array, axes) Parameters : 1d_func : the required function to perform over 1D array. It can only be applied in 1D slices of input array and that too along a particular axis. a
3 min read
numpy.column_stack() in Python
numpy.column_stack() function is used to stack 1-D arrays as columns into a 2-D array.It takes a sequence of 1-D arrays and stack them as columns to make a single 2-D array. 2-D arrays are stacked as-is, just like with hstack function. Syntax : numpy.column_stack(tup) Parameters : tup : [sequence of
2 min read
numpy.full_like() in Python
The numpy.full_like() function return a new array with the same shape and type as a given array.Syntax : numpy.full_like(a, fill_value, dtype = None, order = 'K', subok = True) Parameters : shape : Number of rows order : C_contiguous or F_contiguous dtype : [optional, float(by Default )] Data type o
2 min read
numpy.ones() in Python
The numpy.ones() function returns a new array of given shape and type, with ones. Syntax: numpy.ones(shape, dtype = None, order = 'C') Parameters : shape : integer or sequence of integers order : C_contiguous or F_contiguous C-contiguous order in memory(last index varies the fastest) C order means t
2 min read
numpy.mask_indices() function | Python
numpy.mask_indices() function return the indices to access (n, n) arrays, given a masking function. Syntax : numpy.mask_indices(n, mask_func, k = 0) Parameters : n : [int] The returned indices will be valid to access arrays of shape (n, n). mask_func : [callable] A function whose call signature is s
1 min read
numpy.pad() function in Python
numpy.pad() function is used to pad the Numpy arrays. Sometimes there is a need to perform padding in Numpy arrays, then numPy.pad() function is used. The function returns the padded array of rank equal to the given array and the shape will increase according to pad_width. Syntax: numpy.pad(array, p
2 min read
numpy.matrix() in Python
This class returns a matrix from a string of data or array-like object. Matrix obtained is a specialised 2D array. Syntax : numpy.matrix(data, dtype = None) : Parameters : data : data needs to be array-like or string dtype : Data type of returned array. Returns : data interpreted as a matrix # Pytho
1 min read
numpy.all() in Python
The numpy.all() function tests whether all array elements along the mentioned axis evaluate to True. Syntax: numpy.all(array, axis = None, out = None, keepdims = class numpy._globals._NoValue at 0x40ba726c) Parameters : array :[array_like]Input array or object whose elements, we need to test. axis :
3 min read