Henry Shackleton
Henry Shackleton

Reputation: 391

Iterating through rows in numpy array with one row

For a 2D numpy array A, the loop for a in A will loop through all the rows in A. This functionality is what I want for my code, but I'm having difficulty with the edge case where A only has one row (i.e., is essentially a 1-dimensional array). In this case, the for loop treats A as a 1D array and iterates through its elements. What I want to instead happen in this case is a natural extension of the 2D case, where the loop retrieves the (single) row in A. Is there a way to format the array A such that the for loop functions like this?

Upvotes: 0

Views: 2024

Answers (3)

Merna Mustafa
Merna Mustafa

Reputation: 1373

I think you can use np.expand_dims to achieve your goal

X = np.expand_dims(X, axis=0)

Upvotes: 1

Kasonnara
Kasonnara

Reputation: 121

If your array trully is a 2D array, even with one row, there is no edge case:

import numpy
a = numpy.array([[1, 2, 3]]) 
for line in a:
    print(line)

>>> [1 2 3]

You seem to be confusing numpy.array([[1, 2, 3]]) which is a 2D array of one line and numpy.array([1, 2, 3]) which would be a 1D array.

Upvotes: 1

Luke B
Luke B

Reputation: 1194

Depending on if you declare the array yourself you can do this:

A = np.array([[1, 2, 3]])

Else you can check the dim of your array before iterating over it

B = np.array([1, 2, 3])
if B.ndim == 1:
    B = B[None, :]

Or you can use the function np.at_least2d

C = np.array([1, 2, 3])
C = np.atleast_2d(C)

Upvotes: 1

Related Questions