numpy: syntax/idiom to cast (n,) array to a (n, 1) array?

arrays, casting, numpy, python, vector

Solution

I'd use the following:

a[:,np.newaxis]

An alternative (but perhaps slightly less clear) way to write the same thing is:

a[:,None]

All of the above (including your version) are constant-time operations.

Problem

I'd like to cast a numpy `ndarray` object of shape (n,) into one having shape (n, 1). The best I've come up with is to roll my own _to_col function: ``` def _to_col(a): return a.reshape((a.size, 1)) ``` But it is hard for me to believe that such a ubiquitous operation is not already built into numpy's syntax. I figure that I just have not been able to hit upon the right Google search to find it.

Original source