Vector Stacking¶
import numpy as np
1. concatenate¶
The arrays must have the same shape, except in the dimension corresponding to axis. The default axis along which the arrays will be joined is 0.
x = np.array([["Germany","France"],["Berlin","Paris"]])
y = np.array([["Hungary","Austria"],["Budapest","Vienna"]])
print(x)
print(x.shape)
[['Germany' 'France']
['Berlin' 'Paris']]
(2, 2)
print(y)
print(y.shape)
[['Hungary' 'Austria']
['Budapest' 'Vienna']]
(2, 2)
The default is row-wise concatenation for a 2D array¶
print('Joining two arrays along axis 0')
np.concatenate((x,y))
Joining two arrays along axis 0
array([['Germany', 'France'],
['Berlin', 'Paris'],
['Hungary', 'Austria'],
['Budapest', 'Vienna']], dtype='<U8')
Column-wise¶
print('Joining two arrays along axis 1')
np.concatenate((x,y), axis = 1)
Joining two arrays along axis 1
array([['Germany', 'France', 'Hungary', 'Austria'],
['Berlin', 'Paris', 'Budapest', 'Vienna']], dtype='<U8')
2. stack¶
a = np.array([1, 2, 3])
b = np.array([2, 3, 4])
np.stack((a, b))
array([[1, 2, 3],
[2, 3, 4]])
studentId = np.array([1,2,3,4])
name = np.array(["Alice","Beth","Cathy","Dorothy"])
scores = np.array([65,78,90,81])
np.stack((studentId, name, scores))
array([['1', '2', '3', '4'],
['Alice', 'Beth', 'Cathy', 'Dorothy'],
['65', '78', '90', '81']], dtype='<U21')
np.stack((studentId, name, scores)).shape
(3, 4)
np.stack((studentId, name, scores), axis =1)
array([['1', 'Alice', '65'],
['2', 'Beth', '78'],
['3', 'Cathy', '90'],
['4', 'Dorothy', '81']], dtype='<U21')
np.stack((studentId, name, scores), axis =1).shape
(4, 3)
3. vstack¶
Stacks row wise
np.vstack((studentId, name, scores))
array([['1', '2', '3', '4'],
['Alice', 'Beth', 'Cathy', 'Dorothy'],
['65', '78', '90', '81']], dtype='<U21')
4. hstack¶
Stacks column wise
np.hstack((studentId, name, scores))
array(['1', '2', '3', '4', 'Alice', 'Beth', 'Cathy', 'Dorothy', '65',
'78', '90', '81'], dtype='<U21')
np.hstack((studentId, name, scores)).shape
(12,)
The functions concatenate, stack and block provide more general stacking and concatenation operations.