How to Iterate Through a Matrix Column in Python

Numpy how to iterate over columns of array?

Just iterate over the transposed of your array:

for column in array.T:
some_function(column)

How to iterate through a matrix column in python

You have not specified what the datatype of your matrix is. If it is a list of lists, then there is no way to "get just one column", but the code still is similar (assuming that r and c are of type int):

I added the functionality to only count the cells adjacent to the cell in question (above, below, left and right; does NOT consider diagonals); this is done checking that the difference between indexes is not greater than 1.

count_in_row = 0
count_in_col = 0
value = matrix[r][c]

for j in range(len(matrix[r])):
if abs(j - c) <= 1: # only if it is adjacent
if matrix[r][j] == value:
count_in_row += 1
for i in range(len(matrix)):
if abs(i - r) <= 1: # only if it is adjacent
if matrix[i][c] == value:
count_in_col += 1

Or if following the way you started it (whole rows and columns, not only adjacent ones):

for col_val in matrix[r]:
if col_val == value:
count_in_row += 1
for row in matrix:
if row[c] == value:
count_in_col += 1

If you will be doind this for a lot of cells, then there are better ways to do that (even without numpy, but numpy is defenitively a very good option).

How to iterate over columns of a matrix?

How about

for i in a.transpose():

or, shorter:

for i in a.T:

This may look expensive but is in fact very cheap (it returns a view onto the same data, but with the shape and stride attributes permuted).

iterating over numpy matrix columns

It is better to use 2d np.array instead of matrix.

import numpy as np
data = np.array([[1, 2, 0], [0, 0, 1], [0, 2, 4]], dtype='float')
data[data == 0] = np.nan
# replace all zeroes with `nan`'s to skip them
# [[ 1. 2. nan]
# [ nan nan 1.]
# [ nan 2. 4.]]
np.nanmean(data, axis=0)
# array([ 1. , 2. , 2.5])
np.nanmean(data, axis=1)
# array([ 1.5, 1. , 3. ])

Numpy array: iterate through column and change value depending on the next value

Try this -

data[np.roll(data==101,-1,0)] = 10001
array([[    1,     2,     3],
[ 1, 2, 10001],
[ 1, 2, 101],
[ 4, 5, 111],
[ 4, 5, 6],
[ 4, 5, 10001],
[ 4, 5, 101],
[ 4, 5, 112],
[ 4, 5, 6]])

Only assumption here is that your first row doesn't contain a 101


In case there is a potential scenario that 101 may occur in the first row of the matrix, then try this approach below.

idx = np.vstack([np.roll(data==101,-1,0)[:-1], np.array([False, False, False])])
data[idx] = 10001
array([[    1,     2,     3],
[ 1, 2, 10001],
[ 1, 2, 101],
[ 4, 5, 111],
[ 4, 5, 6],
[ 4, 5, 10001],
[ 4, 5, 101],
[ 4, 5, 112],
[ 4, 5, 6]])

Iterate over numpy array columnwise

For completeness, you don't necessarily have to transpose the matrix before iterating through the elements. With np.nditer you can specify the order of how to iterate through the matrix. The default is usually row-major or C-like order. You can override this behaviour and choose column-major, or FORTRAN-like order which is what you desire. Simply specify an additional argument order and set this flag to 'F' when using np.nditer:

In [16]: x = np.array([[1,3],[2,4]])

In [17]: for i in np.nditer(x,order='F'):
....: print i
....:
1
2
3
4

You can read more about how to control the order of iteration here: http://docs.scipy.org/doc/numpy-1.10.0/reference/arrays.nditer.html#controlling-iteration-order

Iterate through an adjacency matrix with a list

You can use zip and sum as follows (or itertools.pairwise instead of zip in python 3.10+):

import numpy as np

m = np.reshape(range(9), (3, 3)) # an example matrix
print(m)
# [[0 1 2]
# [3 4 5]
# [6 7 8]]

lst = [0, 2, 1, 0]
total_dist = sum(m[i][j] for i, j in zip(lst, lst[1:]))
print(total_dist) # 12


Related Topics



Leave a reply



Submit