0

I have a complex function that returns a 2D array, to make it simple, let's consider the following:

import numpy as np

def get_array():
    a = np.array([[0, 9, 5]])
    return a

Is there a numpy command that allows me to retrieve the single row automatically instead of doing the following?

def get_array():
    a = np.array([[0, 9, 5]])
    if a.shape[0] == 1:
        return a[0]
    else:
        return a 
    return a

Thanks a lot!

1
  • 1
    a.ravel() or a.flatten()... Commented Nov 30, 2021 at 16:56

2 Answers 2

2

np.squeeze(a) will remove any unit sized axes from a.

>>> np.squeeze([1, 2, 3])
array([1, 2, 3])

>>> np.squeeze([[1, 2, 3]])
array([1, 2, 3])

>>> np.squeeze([[1, 2, 3], [4, 5, 6]])
array([[1, 2, 3],
       [4, 5, 6]])

It might not be exactly what you want though, as also:

>>> np.squeeze([[1], [2]])
array([1, 2])
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you @orlp, this is exactly what I need as in my case the 2D array is (Nx3)
@mauro If my answer solved your problem please consider marking it as accepted.
0

On top of @orlp answer, if you are conscious of performance, ravel seems to be faster than squeeze:

enter image description here

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.