Reputation: 1604
I have a vector and want to reshape it into a matrix, but the lenghts don't match. I want the remaining spots in the matrix to be filled with nan
import numpy
vec = np.arange(7, dtype=float)
mat = np.reshape(vec,(3,3)) # not working since vector too short
desired output:
array([[ 0., 1., 2.],
[ 3., 4., 5.],
[ 6., nan, nan]])
How can I achieve the array without manually extending the vector?
Upvotes: 3
Views: 434
Reputation: 88276
Define an empty NaN
array and update using vec
. This leverages the fact that ravel
returns a view into the array, hence any modifications will be reflected in the actual array:
out = np.full((3,3), np.nan)
out.ravel()[:len(vec)] = vec
print(out)
array([[ 0., 1., 2.],
[ 3., 4., 5.],
[ 6., nan, nan]])
Upvotes: 5