Numpy reshape 1d to 2d array with 1 column

Viewed 70548

In numpy the dimensions of the resulting array vary at run time. There is often confusion between a 1d array and a 2d array with 1 column. In one case I can iterate over the columns, in the other case I cannot.

How do you solve elegantly that problem? To avoid littering my code with if statements checking for the dimensionality, I use this function:

def reshape_to_vect(ar):
    if len(ar.shape) == 1:
      return ar.reshape(ar.shape[0],1)
    return ar

However, this feels inelegant and costly. Is there a better solution?

7 Answers

The simplest way:

ar.reshape(-1, 1)

To avoid the need to reshape in the first place, if you slice a row / column with a list, or a "running" slice, you will get a 2D array with one row / column

import numpy as np
x = np.array(np.random.normal(size=(4,4)))
print x, '\n'

Result:
[[ 0.01360395  1.12130368  0.95429414  0.56827029]
 [-0.66592215  1.04852182  0.20588886  0.37623406]
 [ 0.9440652   0.69157556  0.8252977  -0.53993904]
 [ 0.6437994   0.32704783  0.52523173  0.8320762 ]] 

y = x[:,[0]]
print y, 'col vector \n'
Result:
[[ 0.01360395]
 [-0.66592215]
 [ 0.9440652 ]
 [ 0.6437994 ]] col vector 


y = x[[0],:]
print y, 'row vector \n'

Result:
[[ 0.01360395  1.12130368  0.95429414  0.56827029]] row vector 

# Slice with "running" index on a column
y = x[:,0:1]
print y, '\n'

Result:
[[ 0.01360395]
 [-0.66592215]
 [ 0.9440652 ]
 [ 0.6437994 ]] 

Instead if you use a single number for choosing the row/column, it will result in a 1D array, which is the root cause of your issue:

y = x[:,0]
print y, '\n'

Result:
[ 0.01360395 -0.66592215  0.9440652   0.6437994 ] 

A variant of the answer by divakar is: x = np.reshape(x, (len(x),-1)), which also deals with the case when the input is a 1d or 2d list.

There are mainly two ways to go from 1 dimensional array (N) to 2 dimensional array with 1 column
(N x 1):

  1. Indexing with np.newaxis;
  2. Reshape with reshape() method.
x = np.array([1, 2, 3])  # shape: (3,) <- 1d

x[:, None]               # shape: (3, 1) <- 2d (single column matrix)
x[:, np.newaxis]         # shape: (3, 1) <- a meaningful alias to None

x.reshape(-1, 1)         # shape: (3, 1)
y = np.array(12)
y = y.reshape(-1,1)
print(y.shape)

O/P:- (1, 1)
Related