0

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?

3
  • Can you share a minimal example with the behavior you expect? Commented Jul 29, 2020 at 16:24
  • Use np.atleast_2d on A before iterating. Commented Jul 29, 2020 at 16:28
  • I think you needs to differentiate two cases here. If shape(A) = (1, n), i.e., a matrix with a single row, your loop will work just fine. The issue arises if you have a vector, i.e., shape(A) = (n,). You can check len(shape(A)) beforehand and apply a suitable reshape if you only got a vector. Commented Jul 29, 2020 at 16:28

3 Answers 3

2

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

X = np.expand_dims(X, axis=0)
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.