Numpy&Pandas 004: Combination

We have done some basic operations on a array, now, let’s see the combination of two arrays.

Firstly, as usual, make two arrays

1
2
A = np.array([1,1,1])
B = np.array([2,2,2])

Vertical stack

It is pretty easy to combinate them in an array on vertical ,

1
2
3
4
C = np.vstack((A,B))

#array([[1, 1, 1],
# [2, 2, 2]])

And let’s see the shape of it,

1
2
C.shape
#(2, 3)

Horizontal stack

No words…

1
2
3
D = np.hstack((A,B))

#array([1, 1, 1, 2, 2, 2])

And shape,

1
2
D.shape
#(6,)

Now, there is a challenge, we wanna get a special array, like this

1
2
3
4
5
6
7
8
9
10
11
12
array([[1],
[1],
[1],
[1],
[1],
[1],
[2],
[2],
[2],
[2],
[2],
[2]])

We have known we can transpose an array

1
2
A.T
#array([[1,1,1]])

But, the type of it…

1
2
A.T.shape
#(3,)

Same as before, now, we have a new way

1
2
3
4
A[np.newaxis,:]
#array([[1],
# [1],
# [1]])

It seems good, and see the type

1
2
A[np.newaxis,:].shape
#(1, 3)

Successfully, we do half of that special array.

We change A and B to this type

1
2
3
4
5
6
7
8
9
A = A[:,np.newaxis]
B = B[:,np.newaxis]

#array([[1],
# [1],
# [1]])
#array([[2],
# [2],
# [2]])

Can we combinate via last two ways? Absolutely, yes.

Let’s try.

1
2
3
4
5
6
7
8
9
10
11
np.hstack((A,B))
#array([[1, 2],
# [1, 2],
# [1, 2]])
np.vstack((A,B))
#array([[1],
# [1],
# [1],
# [2],
# [2],
# [2]])

Yes, we get that special array type on vertical way.

Is it available for it to combinate more than two arrays?

We have not gotten that special array. Let’s try.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
np.vstack((A,A,B,B))

array([[1],
[1],
[1],
[1],
[1],
[1],
[2],
[2],
[2],
[2],
[2],
[2]])

We get it!!!

Now, let’s see another way, use the function concatenate

Concatenate

We can use this function to do both hstack and vstack that they can do.

1
np.concatenate((A,A,B,B), axis=0)

output:

1
2
3
4
5
6
7
8
9
10
11
12
array([[1],
[1],
[1],
[1],
[1],
[1],
[2],
[2],
[2],
[2],
[2],
[2]])

The 0 is represented as vertical.

If axis = 1,

1
np.concatenate((A,A,B,B), axis=1)

output:

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

It is equal to hstack.

So, if we memory this function, we can do same function as both of hstack and vstack.

Thanks for your reading, I hope it is useful for you.


End

Illustrator / Cagy

Text / Cagy

Editor / Cagy

Design / Cagy