Joining of multiple arrays into a single array
- It is similar to Join queries in Oracle.
- We can join/concatenate multiple ndarrays into a single array by using the following functions.*
- concatenate()
- stack()
- vstack()
- hstack()
- dstack()
concatenate()
Example
import numpy as np
help(np.concatenate)
Output
Help on function concatenate in module numpy:
concatenate(...)
concatenate((a1, a2, ...), axis=0, out=None, dtype=None, casting="same_kind")
Join a sequence of arrays along an existing axis.
Syntax
concatenate(…)
- concatenate((a1, a2, …), axis=0, out=None, dtype=None, casting=”same_kind”).
- Join a sequence of arrays along an existing axis.
(a1, a2,..) ==> input arrays along an existing axis
axis ==> based on which axis we have to perform concatination
- axis=0(default) :: vertical concatination will happens.
- axis=1 :: Horizontal concatination will happens.
- axis=None :: First the arrays will be flatten(converted to 1-D array) and then concatination will be performed on the resultant arrays.
out ==> destination array, where we have to store concatenation result.
Example
# 1-D array
import numpy as np
a = np.arange(4)
b = np.arange(5)
c = np.arange(3)
np.concatenate((a,b,c))
Output
array([0, 1, 2, 3, 0, 1, 2, 3, 4, 0, 1, 2])
Example
# 2-D array
import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
# concatination by providing axis paraameter
# Vertical Concatenation
vcon = np.concatenate((a,b))
Output
nhi diya h
Example
vcon1 = np.concatenate((a,b),axis=0)
# Horizontal Concateation
hcon = np.concatenate((a,b),axis=1)
# flatten and then concatenation
flatt = np.concatenate((a,b),axis=None)
print(f"array a ==> \n {a}")
print(f"array b ==> \n {b}")
print(f"Without specifying axis parameter ==> \n {vcon}")
print(f"Specifying axis=0 a ==> \n {vcon1}")
print(f"Specifying axis=1 ==> \n {hcon}")
print(f"Specifying axis=None ==> \n {flatt}")
Output
array a ==>
[[1 2]
[3 4]]
array b ==>
[[5 6]
[7 8]]
Without specifying axis parameter ==>
[[1 2]
[3 4]
[5 6]
[7 8]]
Specifying axis=0 a ==>
[[1 2]
[3 4]
[5 6]
[7 8]]
Specifying axis=1 ==>
[[1 2 5 6]
[3 4 7 8]]
Specifying axis=None ==>
[1 2 3 4 5 6 7 8]
Rules
- We can join any number of arrays, but all arrays should be of same dimension.
- The sizes of all axes, except concatenation axis should be same.
- The shapes of resultant array and out array must be same.
Example
# Rule-2 demonstration
import numpy as np
a = np.arange(6).reshape(2,3)
b = np.arange(15).reshape(5,3)
print(f"array a ==> \n {a}")
print(f"array b ==> \n {b}")
# axis=0 ==> Vertical concatenation
vcon = np.concatenate((a,b),axis=0)
print(f"Vertical Concatenation array ==> \n{vcon}")
# axis=1 ==> Horizontal Concatenation
hcon = np.concatenate((a,b),axis=1)
print(f"Horizontal Concatenation array ==> \n{hcon}")
Output
array a ==>
[[0 1 2]
[3 4 5]]
array b ==>
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]
[12 13 14]]
Vertical Concatenation array ==>
[[ 0 1 2]
[ 3 4 5]
[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]
[12 13 14]]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-258-e115434e606d> in <module>
12
13 # axis=1 ==> Horizontal Concatenation
---> 14 hcon = np.concatenate((a,b),axis=1)
15 print(f"Horizontal Concatenation array ==> \n{hcon}")
<__array_function__ internals> in concatenate(*args, **kwargs)
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 0, the array at index 0 has size2 and the array at index 1 has size 5.
Storing the result using ‘out’ parameter
- concatenate(…)
- concatenate((a1, a2, …), axis=0, out=None, dtype=None, casting=”same_kind”).
- Join a sequence of arrays along an existing axis .
- we can store result in an array after concatenation using ‘out’ parameter, but the result and out must be in same shape.
Example
# example for out parameter
import numpy as np
a = np.arange(4)
b = np.arange(5)
c = np.empty(9) # default dtype for empty is float
np.concatenate((a,b),out=c)
Output
array([0., 1., 2., 3., 0., 1., 2., 3., 4.])
Example
c
Output
array([0., 1., 2., 3., 0., 1., 2., 3., 4.])
Example
# if the shape of result and out differs then we will get error : ValueError
import numpy as np
a = np.arange(4)
b = np.arange(5)
c = np.empty(10) # default dtype is float
np.concatenate((a,b),out=c)
Output
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-261-580400b85648> in <module>
4 b = np.arange(5)
5 c = np.empty(10) # default dtype is float
----> 6 np.concatenate((a,b),out=c)
<__array_function__ internals> in concatenate(*args, **kwargs)
ValueError: Output array is the wrong shape
using 'dtype' parameter
we can specifyt the required data type using dtype parameter
using ‘dtype’ parameter
- we can specifyt the required data type using dtype parameter.
Example
# Demo for dtype parameter
import numpy as np
a = np.arange(4)
b = np.arange(5)
np.concatenate((a,b),dtype=str)
Output
array(['0', '1', '2', '3', '0', '1', '2', '3', '4'], dtype='<U11')
Note
- We can use either out or dtype .
- We cannot use both out and dtype simultaneously because out has its own data type.
Example
# Demo for both out dtype parameter
import numpy as np
a = np.arange(4)
b = np.arange(5)
c = np.empty(9,dtype=str)
np.concatenate((a,b),out=c,dtype=str)
Output
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-263-67ff4979a9b2> in <module>
4 b = np.arange(5)
5 c = np.empty(9,dtype=str)
----> 6 np.concatenate((a,b),out=c,dtype=str)
<__array_function__ internals> in concatenate(*args, **kwargs)
TypeError: concatenate() only takes `out` or `dtype` as an argument, but both were provided.
Concatenation of 1-D arrays
- we can concatenate any number of 1-D arrays at a time.
- For 1-D arrays there exists only one axis i.e., axis-0.
Example
# Demo for concatenation of three 1-D arrays
a = np.arange(4)
b = np.arange(5)
c = np.arange(3)
np.concatenate((a,b,c),dtype=int)
Output
array([0, 1, 2, 3, 0, 1, 2, 3, 4, 0, 1, 2])
Concatenation of 2-D arrays
- we can concatenate any number of 2-D arrays at a time.
- For 2-D arrays there exists two axes i.e., axis-0 and axis-1.
axis-0 ==> represents number of rows
axis-1 ==> represents number of columns
- we can perform concatenation either axis-0 or axis-1.
- size of all dimensions(axes) must be matched except concatenation axis.
Example
# Demo for concatenation of two 2-D arrays
import numpy as np
a = np.array([[10,20],[30,40],[50,60]])
b = np.array([[70,80],[90,100]])
print(f"a array :: \n {a}")
print(f"b array :: \n {b}")
print(f"a shape : {a.shape}")
print(f"b shape : {b.shape}"]
# concatenation on axis=0 ==> Vertical concatenation
vcon = np.concatenate((a,b),axis=0)
print(f"Concatenation based on axis-0(vertical) :: \n {vcon}")
# concatenation on axis=0 ==> Horizontal concatenation
hcon = np.concatenate((a,b),axis=1)
print(f"Concatenation based on axis-1(vertical) :: \n {hcon}")
Output
a array ::
[[10 20]
[30 40]
[50 60]]
b array ::
[[ 70 80]
[ 90 100]]
a shape : (3, 2)
b shape : (2, 2)
Concatenation based on axis-0(vertical) ::
[[ 10 20]
[ 30 40]
[ 50 60]
[ 70 80]
[ 90 100]]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-265-cd0ec72a4bb8> in <module>
14
15 # concatenation on axis=0 ==> Horizontal concatenation
---> 16 hcon = np.concatenate((a,b),axis=1)
17 print(f"Concatenation based on axis-1(vertical) :: \n {hcon}")
<__array_function__ internals> in concatenate(*args, **kwargs)
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 0, the array at index 0 has size 3 and the array at index 1 has size 2.
Concatenation of 3-D arrays
- we can concatenate any number of 3-D arrays at a time.
- For 3-D arrays there exists three axes i.e., axis-0,axis-1 and axis-2.
axis-0 ==> represents number of 2-D arrays.
axis-1 ==> represents number of rows in every 2-D array.
axis-2 ==> represents number of columns in every 2-D array.
- we can perform concatenation on axis-0, axis-1, axis-2 (existing axis).
- size of all dimensions(axes) must be matched except concatenation axis.
Example
# Demo for concatenation of 3-D arrays
import numpy as np
a = np.arange(12).reshape(2,3,2)
b = np.arange(18).reshape(2,3,3)
print(f"array a : \n {a}")
print(f"array b : \n {b}")
# concatenation along axis=0 ==> not possible in this case
np.concatenate((a,b),axis=0)
Output
array a :
[[[ 0 1]
[ 2 3]
[ 4 5]]
[[ 6 7]
[ 8 9]
[10 11]]]
array b :
[[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]]
[[ 9 10 11]
[12 13 14]
[15 16 17]]]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-266-ae4dcfa205e6> in <module>
7
8 # concatenation along axis=0 ==> not possible in this case
----> 9 np.concatenate((a,b),axis=0)
<__array_function__ internals> in concatenate(*args, **kwargs)
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 2, the array at index 0 has size 2 and the array at index 1 has size 3
Example
# concatenation along axis=2 ==> possible in this case
np.concatenate((a,b),axis=2)
Output
array([[[ 0, 1, 0, 1, 2],
[ 2, 3, 3, 4, 5],
[ 4, 5, 6. 7, 8]],
[[ 6, 7, 9, 10, 11],
[ 8, 9, 12, 13, 14],
[10,11, 15, 16, 17]]])
Example
# Demo for concatenation of 3-D array in all axes
import numpy as np
a = np.arange(18).reshape(2,3,3)
b = np.arange(18,36).reshape(2,3,3)
print(f"array a : \n {a}")
print(f"array b : \n {b}")
print(f"array a shape: {a.shape}")
print(f"array b shape: {b.shape}")
Output
array a :
[[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]]
[[ 9 10 11]
[12 13 14]
[15 16 17]]]
array b :
[[[18 19 20]
[21 22 23]
[24 25 26]]
[[27 28 29]
[30 31 32]
[33 34 35]]]
array a shape:(2, 3, 3)
array b shape:(2, 3, 3)
Example
# concatenation along axis-0
axis0_result = np.concatenate((a,b),axis=0)
print(f"Concatenation along axis-0 : \n {axis0_result}")
print(f"Shape of the resultant array : {axis0_result.shape}")
Output
Concatenation along axis-0 :
[[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]]
[[ 9 10 11]
[12 13 14]
[15 16 17]
[[18 19 20]
[21 22 23]
[24 25 26]]
[[27 28 29]
[30 31 32]
[33 3435]]]
Shape of the resultant array : (4, 3, 3)
Example
# concatenation along axis-1
axis1_result = np.concatenate((a,b),axis=1)
print(f"Concatenation along axis-0 : \n {axis1_result}")
print(f"Shape of the resultant array : {axis1_result.shape}")
Output
Concatenation along axis-0 :
[[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[18 19 20]
[21 22 23]
[24 25 26]]
[[ 9 10 11]
[12 13 14]
[15 16 17]
[27 28 29]
[30 31 32]
[33 34 35]]]
Shape the resultant array : (2, 6, 3)
Example
# concatenation along axis-2
axis2_result = np.concatenate((a,b),axis=2)
print(f"Concatenation along axis-0 : \n {axis2_result}")
print(f"Shape of the resultant array : {axis2_result.shape}")
Output
Concatenation along axis-0 :
[[[ 0 1 2 18 19 20]
[ 3 4 5 21 22 23]
[ 6 7 8 24 25 26]]
[[ 9 10 11 27 28 29]
[12 13 14 30 31 32]
[15 16 17 33 34 35]]]
Shape of the resultant array : (2, 3, 6)
Summary
If we concatenate any n-D array the result will be same as the input array dimension.
- 1-D + 1-D = 1-D
- 2-D + 2-D = 2-D
- 3-D + 3-D = 3-D
Concatenation is always based on existing axis.
All input arrays must be in same dimension.
For 2-D arrays after concatenation
- For axis-0 ==> number of 2-D arrays are increased and rows and columns remain unchanged.
- For axis-1 ==> Number of rows will be increased and the 2-D arrays and columns unchanged.
- For axis-2 ==> Number of columns will be increased and the 2-D arrays and row unchanged.
Note
- Is it possible to concatenate arrays with shapes (3,2,3) and (2,1,3)?.
- Not possible to concatenate on any axis.
- But axis=None is possible. In this case both arrays will be flatten to 1-D and then concatenation will be happend.
stack()
- All input arrays must have same shape.
- The resultant stacked array has one more dimension than the input arrays.
- The joining is always based on new axis of the newly created array.
1-D + 1-D = 2-D
2-D + 2-D = 3-D
Example
# help on stack
import numpy as np
help(np.stack)
Output
Help on function stack in module numpy:
stack(arrays, axis=0, out=None)
Join a sequence of arrays along a new axis.
The ``axis`` parameter specifies the index of the new axis in the dimensions of the result. For example, if ``axis=0`` it will be the first dimension and if ``axis=-1`` it will be the last dimension.
Stacking 1-D array
- To use stack() method, make sure all input arrays must have same shape, otherwise we will get error.
Example
import numpy as np
a = np.array([10,20,30])
b = np.array([40,50,60,70])
np.stack((a,b))
Output
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-274-4046b86fb736> in <module>
3 a = np.array([10,20,30])
4 b = np.array([40,50,60,70])
----> 5 np.stack((a,b))
<__array_function__ internals> in stack(*args, **kwargs)
F:\Users\Gopi\anaconda3\lib\site-packages\numpy\core\shape_base.py in stack(a
rrays, axis, out)
425 shapes = {arr.shape for arr in arrays}
426 if len(shapes) != 1:
--> 427 raise ValueError('all input arrays must have the same shape')
428
429 result_ndim = arrays[0].ndim + 1
ValueError: all input arrays must have the same shape.
Stacking between 1-D arrays
- The resultant array will be one more dimension i.e., 2-D array.
- Newly created array is 2-D and it has two axes ==> axis-0 and axis-1.
- so we can perform stacking on axis-0 and axis-1.
Stacking along axis=0 in 1-D array
- Axis-0 means stack elements of input array row wise
- Read row wise from input arrays and arrange row wise in result array.
Example
# stacking using axis=0
a = np.array([10,20,30])
b = np.array([40,50,60])
resultant_array = np.stack((a,b)) # default axis=0
print(f"Resultant array : \n {resultant_array}")
print(f"Resultant array shape: {resultant_array.shape}")
Output
Resultant array :
[[10 20 30]
[40 50 60]]
Resultant array shape: (2, 3)
Stacking along axis=1 in 1-D array
- axis-1 means stack elements of input array column wise.
- Read row wise from input arrays and arrange column wise in result array.
Example
# stacking using axis=1
a = np.array([10,20,30])
b = np.array([40,50,60])
resultant_array=np.stack((a,b),axis=1)
print(f"Resultant array : \n {resultant_array}")
print(f"Resultant array shape: {resultant_array.shape}")
Output
Resultant array :
[[10 40]
[20 50]
[30 60]]
Resultant array shape: (3, 2)
Stacking 2-D array
The resultant array will be: 3-D array.
3-D array shape:(x,y,z).
- x–>axis-0 —->The number of 2-D arrays.
- y–>axis-1 —->The number of rows in every 2-D array.
- z–>axis-2 —-> The number of columns in every 2-D array.
axis-0 means 2-D arrays one by one.
axis-1 means row wise in each 2-D array.
axis-2 means column wise in each 2-D array.
figar banana
Example
# stacking of 2-D arrays ==> axis=0
# axis-0 means 2-D arrays one by one:
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
b = np.array([[7,8,9],[10,11,12]])
np.stack((a,b)) # by defulat np.stack((a,b),axis=0)
Output
Out[277]:
array([[[ 1, 2, 3],
[ 4, 5, 6],
[[ 7, 8, 9],
[10, 11, 12]]])
figar banana
Example
# stacking of 2-D arrays ==> axis=1
# axis-1 means row wise in each 2-D array
a = np.array([[1,2,3],[4,5,6]])
b = np.array([[7,8,9],[10,11,12]])
np.stack((a,b),axis=1)
Output
array([[[ 1, 2, 3],
[ 7, 8, 9]],
[[ 4, 5, 6],
[10, 11, 12]]])
Example
# stacking of 2-D arrays ==> axis=2
# axis-2 means column wise in each 2-D array
a = np.array([[1,2,3],[4,5,6]])
b = np.array([[7,8,9],[10,11,12]])
np.stack((a,b),axis=2)
Output
array([[[ 1, 7],
[ 2, 8],
[ 3, 9]],
[[ 4, 10],
[ 5, 11],
[ 6, 12]]])
Example
# Demo of Stacking of Three 2-D arrays
a = np.arange(1,7).reshape(3,2)
b = np.arange(7,13).reshape(3,2)
c = np.arange(13,19).reshape(3,2)
print(f"array a :\n {a}")
print(f"array b :\n {b}")
print(f"array c :\n {c}")
# stacking along axis-0
# In 3-D array axis-0 means the number of 2-d arrays
axis0_stack = np.stack((a,b,c),axis=0)
print(f"Stacking three 2-D arrays along axis-0:\n {axis0_stack}")
Output
array a :
[[1 2]
[3 4]
[5 6]]
array b :
[[ 7 8]
[ 9 10]
[11 12]]
array c :
[[13 14]
[15 16]
[17 18]]
Stacking three 2-D arrays along axis-0:
[[[ 1 2]
[ 3 4]
[ 5 6]]
[[ 7 8]
[ 9 10]
[11 12]]
[[13 14]
[15 16]
[17 18]]]
Example
# stacking along axis-1
# In 3-D array, axis-1 means the number of rows.
# Stacking row wise
axis1_stack = np.stack((a,b,c),axis=1)
print(f"Stacking three 2-D arrays along axis-1:\n {axis1_stack}")
Output
Stacking three 2-D arrays along axis-1:
[[[ 1 2]
[ 7 8]
[13 14]]
[[ 3 4]
[ 9 10]
[15 16]]
[[ 5 6]
[11 12]
[17 18]]]
Example
# stacking along axis-2
# in 3-D array axis-2 means the number of columns in every 2-D array.
# stacking column wise
axis2_stack = np.stack((a,b,c),axis=2)
print(f"Stacking three 2-D arrays along axis-2:\n {axis2_stack}")
Output
Stacking three 2-D arrays along axis-2:
[[[ 1 7 13]
[ 2 8 14]]
[[ 3 9 15]
[ 4 10 16]]
[[ 5 11 17]
[ 6 12 18]]]
Note
- Reading of arrays row-wise.
- arraning is based on the newly created array axis.
Stacking Three 1-D array
Example
a = np.arange(4)
b = np.arange(4,8)
c = np.arange(8,12)
print(f"array a :{a}")
print(f"array b :{b}")
print(f"array c :{c}")
# We will get 2-D array
# In 2-D array avaialble axes are: axis-0 and axis-1
# Based on axis-0:
# axis-0 in 2-D array means the number of rows
axis0_stack = np.stack((a,b,c),axis=0)
print(f"Stacking three 2-D arrays along axis-0:\n {axis0_stack}")
# Based on axis-1:
# axis-1 in 2-D array means the number of columns
axis1_stack = np.stack((a,b,c),axis=1)
print(f"Stacking three 2-D arrays along axis-1:\n {axis1_stack}")
Output
array a :[0 1 2 3]
array b :[4 5 6 7]
array c :[ 8 9 10 11]
Stacking three 2-D arrays along axis-0:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Stacking three 2-D arrays along axis-1:
[[ 0 4 8]
[ 1 5 9]
[ 2 6 10]
[ 3 7 11]]
cancatenate() Vs stack()
cancatenate() | stack() |
Joining will be happened based on existing axis. | Joining will be happened based on new axis. |
The dimension of newly created array is same as input array dimension. | The dimension of newly created array is one more than input array dimension. |
To perform concafenation, all input arrays must have same dimension,the sizes of dimension except concatenation axis must be same. | To perform stack operation, compulsory all input arrays must have same shape.ie dimension,sizes also needs to be same. |
vstack()
- Vstack—>vertical stack—>joining is always based on axis-0.
- For 1-D arrays—>2-D array as output.
- For the remaining dimensions it acts as concatenate() along axis-0.
Rules:
- The input arrays must have the same shape along all except first axis(axis-0).
- 1-D arrays must have the same size.
- The array formed by stacking the given arrays, will be at least 2-D.
- Vstack() operation is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N).
- For 2-D or more dimension arrays, vstack() simply acts as concatenation wrt axis-0.
Example
import numpy as np
help(np.vstack)
Output
Help on function vstack in module numpy:
vstack(tup)
Stack arrays in sequence vertically (row wise).
This is equivalent to concatenation along the first axis after 1-D arrays of shape `(N,)` have been reshaped to `(1,N)`. Rebuilds arrays divided by `vsplit`.
For 1-D arrays
Example
# vstack for 1-D arrays of same sizes
a = np.array([10,20,30,40])
b = np.array([50,60,70,80])
# a will be converted to shapes (1,4) and b will be converted to (1,4)
np.vstack((a,b))
Output
array([[10, 20, 30, 40],
[50, 60, 70, 80]])
Example
# vstack for 1-D arrays of different sizes
a = np.array([10,20,30,40])
b = np.array([50,60,70,80,90,100])
# a will be converted to shapes (1,4) and b will be converted to (1,6)
np.vstack((a,b))
Output
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-286-7aa2c1e1cd41> in <module>
3 b = np.array([50,60,70,80,90,100])
4 # a will be converted to shapes (1,4) and b will be converted to (1,6
)
----> 5 np.vstack((a,b))
<__array_function__ internals> in vstack(*args, **kwargs)
F:\Users\Gopi\anaconda3\lib\site-packages\numpy\core\shape_base.py in vstack(tup)
281 if not isinstance(arrs, list):
282 arrs = [arrs]
--> 283 return _nx.concatenate(arrs, 0)
284
285
<__array_function__ internals> in concatenate(*args, **kwargs)
ValueError: all the input array dimensions for the concatenation axis must ma
tch exactly, but along dimension 1, the array at index 0 has size 4 and the array at index 1 has size 6.
For 2-D arrays
Example
# vstack of 2-D arrays. sizes of axis-1 should be same to perform vstack() ->
concatenation rule
# Here it is possible because sizes of axis-1 are same 3 and 3
# vstack() performed always along axis-0
a = np.arange(1,10).reshape(3,3)
b = np.arange(10,16).reshape(2,3)
np.vstack((a,b))
Output
array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12],
[13, 14, 15]])
Example
# vstack of 2-D arrays. sizes of axis-1 should be same to perform vstack() ->
concatenation rule
# Here it is not possible because sizes of axis-1 are same 3 and 2
# vstack() performed always along axis-0
a = np.arange(1,10).reshape(3,3)
b = np.arange(10,16).reshape(3,2)
np.vstack((a,b))
Output
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-288-4d14bef5f20b> in <module>
4 a = np.arange(1,10).reshape(3,3)
5 b = np.arange(10,16).reshape(3,2)
----> 6 np.vstack((a,b))
<__array_function__ internals> in vstack(*args, **kwargs)
F:\Users\Gopi\anaconda3\lib\site-packages\numpy\core\shape_base.py in vstack(tup)
281 if not isinstance(arrs, list):
282 arrs = [arrs]
--> 283 return _nx.concatenate(arrs, 0)
284
285
<__array_function__ internals> in concatenate(*args, **kwargs)
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 3 and the array at index 1 has size 2.
For 3-D arrays
- axis-0 means The number of 2-D arrays.
Example
a = np.arange(1,25).reshape(2,3,4)
b = np.arange(25,49).reshape(2,3,4)
print(f"array a : \n {a}")
print(f"array b : \n {b}")
result = np.vstack((a,b))
print(f"Result of vstack : \n {result}")
Output
array a :
[[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[13 14 15 16]
[17 18 19 20]
[21 22 23 24]]]
array b :
[[[25 26 27 28]
[29 30 31 32]
[33 34 35 36]]
[[37 38 39 40]
[41 42 43 44]
[45 46 47 48]]]
Result of vstack :
[[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[13 14 15 16]
[17 18 19 20]
[21 22 23 24]]
[[25 26 27 28]
[29 30 31 32]
[33 34 35 36]
[[37 38 39 40]
[41 42 43 44]
[45 46 47 48]]]
hstack()
- Exactly same as concatenate() but joining is always based on axis-1.
- hstack—>horizontal stack—>column wise.
- 1-D + 1-D —>1-D.
Rules:
- This is equivalent to concatenation along the second axis, except for 1-D arrays where it concatenates along the first axis.
- All input arrays must be same dimension.
- Except axis-1, all remining sizes must be equal.
Example
import numpy as np
help(np.hstack)
Output
Help on function hstack in module numpy:
hstack(tup)
Stack arrays in sequence horizontally (column wise).
This is equivalent to concatenation along the second axis, except for 1-D arrays where it concatenates along the first axis. Rebuilds arrays divided by `hsplit`.
For 1-D arrays
Example
a = np.array([10,20,30,40])
b = np.array([50,60,70,80,90,100])
np.hstack((a,b))
Output
array([ 10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
For 2-D arrays
Example
a = np.arange(1,7).reshape(3,2)
b = np.arange(7,16).reshape(3,3)
np.hstack((a,b))
Output
array([[ 1, 2, 7, 8, 9],
[ 3, 4, 10, 11, 12],
[ 5, 6, 13, 14, 15]])
Example
a = np.arange(1,7).reshape(2,3)
b = np.arange(7,16).reshape(3,3)
np.hstack((a,b))
Output
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-293-0e470a6aee78> in <module>
1 a = np.arange(1,7).reshape(2,3)
2 b = np.arange(7,16).reshape(3,3)
----> 3 np.hstack((a,b))
<__array_function__ internals> in hstack(*args, **kwargs)
F:\Users\Gopi\anaconda3\lib\site-packages\numpy\core\shape_base.py in hstack(tup)
344 return _nx.concatenate(arrs, 0)
345 else:
--> 346 return _nx.concatenate(arrs, 1)
347
348
<__array_function__ internals> in concatenate(*args, **kwargs)
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 0, the array at index 0 has size 2 and the array at index 1 has size 3
dstack()
- Dstack() —>depth/height stack —>concatenation based on axis-2.
- 1-D and 2-D arrays will be converted to 3-D array.
- The result is minimum 3-D array.
Rules:
- This is equivalent to concatenation along the third axis after 2-D arrays of shape (M,N) have been reshaped to (M,N,1) and 1-D arrays of shape (N,) have been reshaped to (1,N,1).
- The arrays must have the sam e shape along all but the third axis.
1-D or 2-D arrays must have the same shape.
- The array formed by stacking the given arrays, will be at least 3-D.
Example
import numpy as np
help(np.dstack )
Output
Help on function dstack in module numpy:
dstack(tup)
Stack arrays in sequence depth wise (along third axis).
This is equivalent to concatenation along the third axis after 2-D arrays of shape `(M,N)` have been reshaped to `(M,N,1)` and 1-D arrays of shape `(N,)` have been reshaped to `(1,N,1)`. Rebuilds arrays divided by`dsplit`.
Example
a = np.array([1,2,3])
b = np.array([2,3,4])
np.dstack((a,b))
Output
array([[[1, 2],
[2, 3],
[3, 4]]])
Example
a = np.array([[1],[2],[3]])
b = np.array([[2],[3],[4]])
np.dstack((a,b))
Output
array([[[1, 2]],
[[2, 3]],
[[3, 4]]])
Summary of joining of nd arrays:
- concatenate() ==> Join a sequence of arrays along an existing axis.
- stack() => Join a sequence of arrays along a new axis.
- vstack() => Stack arrays in sequence vertically according to first axis (axis-0).
- hstack() => Stack arrays in sequence horizontally according to second axis(axis-1).
- hstack() => Stack arrays in sequence horizontally according to second axis(axis-1).