J_yang
J_yang

Reputation: 2812

Numpy, how to reshape a vector to multi column array

I am wondering how to use np.reshape to reshape a long vector into n columns array without giving the row numbers.

Normally I can find out the row number by len(a)//n:

a = np.arange(0, 10)
n = 2
b = a.reshape(len(a)//n,n)

If there a more direct way without using len(a)//n?

Upvotes: 1

Views: 1616

Answers (1)

Thibault D.
Thibault D.

Reputation: 1637

You can use -1 on one dimension, numpy will figure out what this number should be:

a = np.arange(0, 10)
n = 2
b = a.reshape(-1, n)

The doc is pretty clear about this feature: https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html

One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

Upvotes: 9

Related Questions