Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stacking numpy arrays?

I am trying to stack arrays horizontally, using numpy hstack, but can't get it to work. Instead, it all comes out in one list, instead of a 'matrix-looking' 2D array.

import numpy as np
y = np.array([0,2,-6,4,1])
y_bool = y > 0
y_bool = [1 if l == True else 0 for l in y_bool] #convert to decimals for classification
y_range = range(0,len(y))
print y
print y_bool
print y_range
print np.hstack((y,y_bool,y_range))

Prints this:

[ 0  2 -6  4  1]
[0, 1, 0, 1, 1]
[0, 1, 2, 3, 4]
[ 0  2 -6  4  1  0  1  0  1  1  0  1  2  3  4]

How do I instead get the last line to look like this:

[0 0 0
 2 1 1
-6 0 2
 4 1 3]
like image 668
Zach Avatar asked Mar 08 '26 02:03

Zach


2 Answers

If you want to create a 2D array, do:

print np.transpose(np.array((y, y_bool, y_range)))
# [[ 0  0  0]
#  [ 2  1  1]
#  [-6  0  2]
#  [ 4  1  3]
#  [ 1  1  4]]
like image 51
David Robinson Avatar answered Mar 09 '26 16:03

David Robinson


Well, close enough h is for horizontal/column wise, if you check its help, you will see under See Also

vstack : Stack arrays in sequence vertically (row wise).
dstack : Stack arrays in sequence depth wise (along third axis).
concatenate : Join a sequence of arrays together.

Edit: First thought vstack does it, but it would be if np.vstack(...).T or np.dstack(...).squeeze(). Other then that the "problem" is that the arrays are 1D and you want them to act like 2D, so you could do:

print np.hstack([np.asarray(a)[:,np.newaxis] for a in (y,y_bool,y_range)])

the np.asarray is there just in case one of the variables is a list. The np.newaxis makes them 2D to make it clearer what happens when concatenating.

like image 21
seberg Avatar answered Mar 09 '26 17:03

seberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!