pythonnumpy

Convert numpy array in column vector


I am new to python programming so excuse me if the question may seem silly or trivial.

So for a certain function I need to do a check in case x is a vector and (in that case) it must be a column vector. However I wanted to make it so that the user could also pass it a row vector and turn it into a column vector.

However at this point how do I make it not do the check if x is a scalar quantity.

I attach a code sketch to illustrate the problem. Thanks in advance to whoever responds

import numpy as np

x = np.arange(80, 130, 10)
# x: float = 80.0
print('array before:\n', x)

if x is not np.array:
    x = np.array(x).reshape([len(x), 1])

print('array after:\n', x)

Solution

  • You can check the type using if not isinstance(x, np.ndarray). After that check you can check the number of dimension of the array and convert to a columnar array.

    In the code below, first if block checks and converts to an array. Then we get how many dimensions are missing. I.e. a scalar value is missing 2 dimensions, a flat list is missing 1 dimension. Finally we iterate over the number of missing dimensions up-converting the array's dimensions with each step.

    def to_column_array(x):
        if not isinstance(x, np.ndarray):
            x = np.array(x)
    
        missing_dims = 2 - x.ndim
        if missing_dims < 0:
            raise ValueError('You array has too many dimensions')
    
        for _ in range(missing_dims):
            x = x.reshape(-1, 1)
        return x
    

    So if a user has just a number, this convert it to an array of size (1, 1).

    to_column_array(10)
    # returns:
    array([[10]])
    

    Passing in a list or list of lists converts to an array as well.

    to_column_array([3, 6, 9])
    # returns:
    array([[3],
           [6],
           [9]])
    
    to_column_array([[1, 2], [3, 4], [5, 6])
    # returns:
    array([[1, 2],
           [3, 4],
           [5, 6]])