user11074017
user11074017

Reputation:

NumPy: is there a better way to construct a specific matrix with specific value?

I've managed to construct a matrix with this piece of code

c_bed = np.append(np.array([1, 2, 3]), np.nan).reshape(4, 1)
c_bath = np.array([1, 1, 2, 2], dtype=np.float).reshape(4, 1)
ds = np.append(c_bed, c_bath, axis=1)

which gives

array([[ 1.,  1.],
       [ 2.,  1.],
       [ 3.,  2.],
       [nan,  2.]])

the output is exactly what i want though, I am wondering is there a better way to construct this matrix?

Upvotes: 2

Views: 75

Answers (4)

Paul Panzer
Paul Panzer

Reputation: 53089

Disclaimer: the following may well be the shortest method, but it is most certainly not the healthiest. I wouldn't use it in production code.

np.c_[[2,4,6,np.nan],2:6]//2
# array([[ 1.,  1.],
#        [ 2.,  1.],
#        [ 3.,  2.],
#        [nan,  2.]])

Upvotes: 0

BENY
BENY

Reputation: 323366

How about using zip_longest

from itertools import zip_longest
np.array(list(zip_longest([1,2,3],[1,1,2,2],fillvalue=np.nan)))
Out[228]: 
array([[ 1.,  1.],
       [ 2.,  1.],
       [ 3.,  2.],
       [nan,  2.]])

Upvotes: 1

Mad Physicist
Mad Physicist

Reputation: 114518

If you have

beds = [1, 2, 3]
baths = [1, 1, 2, 2]
data = (beds, baths)

You can do as follows:

ds = np.full((max(map(len, data)), 2), np.nan)
ds[:len(beds), 0] = beds
ds[:len(baths), 1] = baths

Upvotes: 1

Patol75
Patol75

Reputation: 4547

Is there any reason not to use this matrix = numpy.array([[1, 1], [2, 1], [3, 2], [numpy.nan, 2]])?

Upvotes: 1

Related Questions