2

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?

4 Answers 4

1

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.]])
Sign up to request clarification or add additional context in comments.

2 Comments

Set fillvalue=np.nan and you get a numerical array.
np.array(list(zip_longest([1,2,3],[1,1,2,2])),'d') also works.
1

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

2 Comments

I think the assumption is that the original lists are incoming data
I am happy to update my answer if the OP demonstrates it is the case.
1

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

Comments

0

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.]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.