IKH

Chapter-9

Array Manipulation function

reshape9()function

  • We can use reshape() function to change array shape without changing data.

Syntax

reshape(a, newshape, order=’C’)

  • Gives a new shape to an array without changing its data.
  • newshape : int or tuple of ints
  • order : {‘C’, ‘F’, ‘A’}
  • Default value for the order: ‘C’
  • ‘C’ ==> C language style which means row major order.
  • ‘F’ ==> Fortran language style which means column major order.
  • The Data should not be changed. Input size and output size shoule be matched, other-wise we will get the ValueError
  • No chnage in the data. So new object won’t be created. We will get just View. If we perform any change in the original array, that change will be reflected to reshaped array and vice-versa
  • We can specify unknown dimension size as -1, but only once.

reshape(a, newshape, order=’C’)

  • C style ==> Row major order(default) : it will consider 1st row, 2nd row and so on
  • Fortran Style(F) ==> Column major order : it will considier 1st column, 2nd column and so on

We can use either reshape() function of the numpy array or reshape() method of
ndarray

  • np.reshape(a,new_shape) ==> Functional style
  • ndarray_obj.reshape(new_shape) ==> Object oriented style

Example

Python
In [203]:
# one shape to any other shape
# (10,) --> (5,2),(2,5),(10,1),(1,10) ==> any no. of views
# (24,) --> (3,8), (6,4),(2,3,4), (2,2,2,4) all are valid

Output

ndarray class also contains reshape() method and hence we can call this method on
any ndarray object.

  • numpy ==> module
  • ndarray ==> class present in numpy module
  • reshape() ==> method present in ndarray class
  • reshape() ==> function present in numpy module.
    numpy.reshape() ==> numpy library function
  • b = np.reshape(a,shape,order)
    ndarray.reshape()—->ndarray object method
  • b = a.reshape(shape,order)
    by using np.reshape() ==> Functional Style

Example

Python
In [204]:
# While using reshape() function, make sure the sizes should be matched otherwise we will get error.
import numpy as np
a = np.arange(1,11)
print(f"array : {a}")
b = np.reshape(a,(5,3))

Output

PowerShell
array : [ 1 2 3 4 5 6 7 8 9 10]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-204-2a87cd9be4ff> in <module>
 3 a = np.arange(1,11)
 4 print(f"array : {a}")
----> 5 b = np.reshape(a,(5,3))
<__array_function__ internals> in reshape(*args, **kwargs)
F:\Users\Gopi\anaconda3\lib\site-packages\numpy\core\fromnumeric.py in reshap
e(a, newshape, order)
297 [5, 6]])
 298 """
--> 299 return _wrapfunc(a, 'reshape', newshape, order=order)
 300 
 301 
F:\Users\Gopi\anaconda3\lib\site-packages\numpy\core\fromnumeric.py in _wrapf
unc(obj, method, *args, **kwds)
 56 
 57 try:
---> 58 return bound(*args, **kwds)
 59 except TypeError:
 60 # A TypeError occurs if the object does have such a method in 
its
ValueError: cannot reshape array of size 10 into shape (5,3)

Example

Python
In [205]:
# converting 1-D array to 2-D array
a = np.arange(1,11)
print(f"array : {a}")
b = np.reshape(a,(5,2))
print(f"Converting 1-D(a) array to 2-D(b) array : \n {b} ")

Output

PowerShell
array : [ 1 2 3 4 5 6 7 8 9 10]
Converting 1-D(a) array to 2-D(b) array : 
[[ 1 2]
[ 3 4]
[ 5 6]
[ 7 8]
[ 9 10]] 

Example

Python
In [206]:
# View is created but not copy Any change in the original array will be reflected to 
the reshaped
# array
a = np.arange(1,16)
b = np.reshape(a,(5,3))
print("*"*80)
print(f"Original array : {a}")
print(f"Reshaped array :\n {b}")
print("*"*80)
print("After modification in the orginal array")
a[0] = 111
print(f"Original array : {a}")
print(f"Reshaped array :\n {b}")
print("*"*80)
print("After modification in the reshaped array")
b[2,1] = 888
print(f"Reshaped array :\n {b}")
print(f"Original array : {a}")
print("*"*80)

Output

PowerShell
Original array : [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]
Reshaped array :
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]
[13 14 15]]
*****************************************************************************
After modification in the orginal array
Original array : [111 2 3 4 5 6 7 8 9 10 11 12 13 14 15
]
Reshaped array :
[[111 2 3]
[ 4 5 6]
[ 7 8 9]
[ 10 11 12]
[ 13 14 15]]
*****************************************************************************
After modification in the reshaped array
Reshaped array :
[[111 2 3]
[ 4 5 6]
[ 7 888 9]
[ 10 11 12]
[ 13 14 15]]
Original array : [111 2 3 4 5 6 7 888 9 10 11 12 13 14 15]
*****************************************************************************
by using ndarray_obj.reshape() ==> Object oriented style

Example

Python
In [207]:
a = np.arange(1,25)
b = a.reshape((2,3,4))
print("*"*80)
print(f"Original array : \n {a}")
print(f"Reshaped array :\n {b}")
print("*"*80)

Output

PowerShell
*****************************************************************************
Original array : 
[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24]
Reshaped array :
[[[ 1 2 3 4]
 [ 5 6 7 8]
 [ 9 10 11 12]]
[[13 14 15 16]
 [17 18 19 20]
 [21 22 23 24]]]
*****************************************************************************

order=’C’

  • C style :: Row major order
  • It will consider 1st row, 2nd row and so on

Example

Python
In [208]:
# C style order :: Row major order
a = np.arange(12)
b = a.reshape((3,4))
print("*"*80)
print(f"Original array : {a}")
print(f"Reshaped array :\n {b}")
print("*"*80)

Output

PowerShell
*****************************************************************************
Original array : [ 0 1 2 3 4 5 6 7 8 9 10 11]
Reshaped array :
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
*****************************************************************************

order=’F’

  • Fortran style :: Column major order
  • It will consider 1st column, 2nd column and so on

Example

Python
In [209]:
# Fortran style order :: Column major order
a = np.arange(12)
b = a.reshape((3,4),order='F')
print("*"*80)
print(f"Original array : {a}")
print(f"Reshaped array :\n {b}")
print("*"*80)

Output

PowerShell
*****************************************************************************
Original array : [ 0 1 2 3 4 5 6 7 8 9 10 11]
Reshaped array :
[[ 0 3 6 9]
[ 1 4 7 10]
[ 2 5 8 11]]
*****************************************************************************

unknown dimension with -1

  • We can use unknown dimension with -1, only once.
  • Numpy will decide and replace -1 with the required dimension
  • we can use any -ve number instead of -1
  • One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions automatically by numpy itself.
  • b = a.reshape((5,-1)) #valid
  • b = a.reshape((-1,5)) #valid
  • b = a.reshape((-1,-1)) #invalid

Example

Python
In [210]:
a = np.arange(1,11)
b = a.reshape((5,-1))
print(f"Shape of array b :: {b.shape}")

Output

PowerShell
Shape of array b :: (5, 2)

Example

Python
In [211]:
a = np.arange(1,11)
b = a.reshape((-1,5))
print(f"Shape of array b :: {b.shape}")

Output

PowerShell
Shape of array b :: (2, 5)

Example

Python
In [212]:
a = np.arange(1,11)
b = a.reshape((-1,-1))

Output

PowerShell
ValueError Traceback (most recent call last)
<ipython-input-212-dbdbcca6ff23> in <module>
 1 a = np.arange(1,11)
----> 2 b = a.reshape((-1,-1))
ValueError: can only specify one unknown dimension

Conclusions of reshape() function

  • To reshape array without changing data.
  • The sizes must be matched
  • We can use either numpy library function(np.reshape()) or ndarray class method(a.reshape())
  • It won’t create a new array object, just we will get view.
  • We can use -1 in the case of unknown dimension, but only once.
  • order: ‘C’,’F’

resize()

Syntax:

numpy.resize(a, new_shape)

  • output array: can be any dimension,any shape,any size
  • input size and output size need not to be matched
  • The data may be changed
  • We will get the copy but the view
  • We can get the new data by np.resize() and a.resize()
  • unknown dimension -1 is not applicable in this resize()

by using np.resize() ==> Functional Style

Syntax: numpy. resize(a, new_shape)

  • If new_size requires more elements repeat elements of the input array
  • new object will be created

Example

Python
In [213]:
a = np.arange(1,6)
b = np.resize(a,(2,4))
print(f"Original array : {a}")
print(f"Reshaped array :\n {b}")

Output

PowerShell
Original array : [1 2 3 4 5]
Reshaped array :
[[1 2 3 4]
[5 1 2 3]]

Example

Python
In [214]:
c = np.resize(a,(2,2))
print(f" array c : \n {c}")

Output

PowerShell
array c : 
[[1 2]
[3 4]]

Example

Python
In [215]:
# original array a is not modified when we call np.resize() function
a

Output

PowerShell
Out[215]:
array([1, 2, 3, 4, 5])

by using ndarray_obj.resize() ==> Object oriented style

Syntax : ndarray_object.resize(new_shape, refcheck=True)

  • If new_size requires more elements then extra elements filled with zeros.
  • If we are using ndarray class resize() method, inline modification will be happend. ie existing array only modifed.

Example

Python
n [216]:
m = np.arange(1,6)
print(f"Original array :\n {m}")
m.resize((4,2))
print(f"After calling resize() method in ndarray :\n {m}")

Output

PowerShell
Original array :
[1 2 3 4 5]
After calling resize() method in ndarray :
[[1 2]
[3 4]
[5 0]
[0 0]]

Example

Python
In [217]:
# original array get modified when we call ndarray_obj.resize() method
m

Output

PowerShell
Out[217]:
array([[1, 2],
 [3, 4],
 [5, 0],
 [0, 0]])

Tabal bnana

tabal bnana

flatten() method

  • We can use flatten() method to flatten(convert) any n-Dimensional array to 1- Dimensional array.

Syntax:

ndarray.flatten(order=’C’)

  • It will create a new 1-Dimensional array with elements of given n-Dimensional
  • array. ie Return a copy of the array collapsed into one dimension.

C-style====>row major order
F-stype===>column major order

  • It is method present in ndarray class but not numpy library function. a.flatten()—>valid np.flatten()–>invalid
  • It will create a new array and returns it (ie copy but not view). If any change is made
  • in the original array it won’t be reflected in flatten copy and vice-versa
  • The output of flatten method is always 1D array

Example

Python
In [218]:
import numpy as np
help(np.flatten)

Output

PowerShell
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-218-c04b96076733> in <module>
 1 import numpy as np
----> 2 help(np.flatten)
F:\Users\Gopi\anaconda3\lib\site-packages\numpy\__init__.py in __getattr__(at
tr)
 301 return Tester
 302 
--> 303 raise AttributeError("module {!r} has no attribute "
 304 "{!r}".format(__name__, attr))
 305 
AttributeError: module 'numpy' has no attribute 'flatten'

Example

Python
In [219]:
help(np.ndarray.flatten)

Output

PowerShell
Help on method_descriptor:
flatten(...)
 a.flatten(order='C')
 
 Return a copy of the array collapsed into one dimension.
 
 Parameters
 ----------
 order : {'C', 'F', 'A', 'K'}, optional
 'C' means to flatten in row-major (C-style) order.
 'F' means to flatten in column-major (Fortran-
 style) order. 'A' means to flatten in column-major
 order if `a` is Fortran *contiguous* in memory,
 row-major order otherwise. 'K' means to flatten
 `a` in the order the elements occur in memory.
 The default is 'C'.

Example

Python
In [220]:
# converting 2-D array to 1-D array ==> C style
a = np.arange(6).reshape(3,2)
b = a.flatten()
print(f"Original array :\n {a}")
print(f"Flatten array :\n {b}")

Output

PowerShell
Original array :
[[0 1]
[2 3]
[4 5]]
Flatten array :
[0 1 2 3 4 5]

Example

Python
In [221]:
# change the value of Original array. The changes wont be reflected in Flatten array
a[0,0] = 8888
print(f"Original array :\n {a}")
print(f"Flatten array :\n {b}")

Output

PowerShell
Original array :
[[8888 1]
[ 2 3]
[ 4 5]]
Flatten array :
[0 1 2 3 4 5]

Example

Python
In [222]:
# converting the 2-D array to 1-D array ==> Fortran style F
a = np.arange(6).reshape(3,2)
b = a.flatten('F')
print(f"Original array :\n {a}")
print(f"Flatten array :\n {b}")

Output

PowerShell
Original array :
[[0 1]
[2 3]
[4 5]]
Flatten array :
[0 2 4 1 3 5]

Example

Python
In [223]:
# Converting 3-D to 1-D ==> C Style
a = np.arange(1,19).reshape(3,3,2)
b = a.flatten()
print(f"Original array :\n {a}")
print(f"Flatten array :\n {b}")

Output

PowerShell
Original array :
[[[ 1 2]
 [ 3 4]
 [ 5 6]]
[[ 7 8]
 [ 9 10]
 [11 12]]
[[13 14]
 [15 16]
 [17 18]]]
Flatten array :
[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18]

Example

Python
In [224]:
# Converting 3-D to 1-D ==> Fortran Style(F)
a = np.arange(1,19).reshape(3,3,2)
b = a.flatten('F')
print(f"Original array :\n {a}")
print(f"Flatten array :\n {b}")

Output

PowerShell
Original array :
[[[ 1 2]
 [ 3 4]
 [ 5 6]]
[[ 7 8]
 [ 9 10]
 [11 12]]
[[13 14]
 [15 16]
 [17 18]]]
Flatten array :
[ 1 7 13 3 9 15 5 11 17 2 8 14 4 10 16 6 12 18]

flat variable

  • It is a 1-D iterator over the array.
  • This is a ‘numpy.flatiter’ instance.
  • ndarray.flat ==> Return a flat iterator over an array.
  • ndarray.flatten ==> Returns a flattened copy of an array.

Example

Python
In [225]:
# help on flatiter
help(np.flatiter)

Output

Example

Python
In [226]:
a = np.arange(1,7).reshape(3,2)
a.flat

Output

PowerShell
Out[226]:
<numpy.flatiter at 0x1aac9a8e770>

Example

Python
In [227]:
a.flat[4]

Output

PowerShell
Out[227]:
5

Example

Python
In [228]:
# iterate over flat
for x in a.flat: print(x)

Output

PowerShell
1
2
3
4
5 
6

ravel() ==> it is a library function in numpy module and a method in ndarray class

It is exactly same as flatten function except that it returns view but not copy.

  • To convert any n-D array to 1-D array.
  • It is method present in ndarray class and also numpy library function. np.ndarray.ravel()—>valid np.ravel()–>valid
  • a.ravel(order=’C’)
    C-style====>row major order
    F-stype===>column major order
  • It returns view but not copy. If we made change in the Original array then the
    changes will be reflected in ravel copy also vice-versa

Note-The output of ravel() method is always 1D array

Example

Python
In [229]:
# Library function help
help(np.ravel)

Output

PowerShell
Help on function ravel in module numpy:
ravel(a, order='C')
 Return a contiguous flattened array.
 
 A 1-D array, containing the elements of the input, is returned.
 A copy is made only if needed.

Example

Python
In [230]:
# ndarray class method help
help(np.ndarray.ravel)

Output

PowerShell
Help on method_descriptor:
ravel(...)
 a.ravel([order])
 
 Return a flattened array.
 
 Refer to `numpy.ravel` for full documentation.
 
 See Also
 --------
 numpy.ravel : equivalent function
 
 ndarray.flat : a flat iterator on the array.

Example

Python
In [231]:
# using ravel() method in ndarray class
a = np.arange(24).reshape(2,3,4)
b = a.ravel()
print(f"Original array :\n {a}")
print(f"Ravel array :\n {b}")

Output

PowerShell
Original array :
[[[ 0 1 2 3]
 [ 4 5 6 7]
 [ 8 9 10 11]]
[[12 13 14 15]
 [16 17 18 19]
 [20 21 22 23]]]
Ravel array :
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]

Example

Python
In [232]:
b[0] = 8888
print(f"Ravel array :\n {b}")
print(f"Original array :\n {a}")

Output

PowerShell
Ravel array :
[8888 1 2 3 4 5 6 7 8 9 10 11 12 13
 14 15 16 17 18 19 20 21 22 23]
Original array 
[[[8888 1 2 3]
 [ 4 5 6 7]
 [ 8 9 10 11]]
[[ 12 13 14 15]
 [ 16 17 18 19]
 [ 20 21 22 23]]]

Example

Python
In [233]:
# using ravel() function in numpy module
a = np.arange(18).reshape(6,3)
b = np.ravel(a)
print(f"Original array :\n {a}")
print(f"Ravel array :\n {b}")

Output

PowerShell
Original array :
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]
[12 13 14]
[15 16 17]]
Ravel array :
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17]

Table

flatten()ravel()
It can used flatten n-D array
to 1-D array and a separate 1-D array object will be created.
If we perform any change in the flatten() copy, then those changes won’t be reflected in the original copy.
flatten() method operates slower than ravel() as it is required to create a new array object
flatten() is not numpy library level function and it is a method present in ndarry class.
ndarrayObj.flatter()->valid
nummpy.flatten()->invalid
transpose() => both numpy library function and ndarray metho
  • In our general mathematics, how to get transpose of given matrix? ==> By interchanging rows and columns.
  • Similarly, to interchange dimensions of nd array, we should go for transpose()
    function.

Syntax:

numpy.transpose(a,axes=None)

  • Reverse or permute the axes of an array; returns the modified array(View but not copy)
  • For an array a with two axes, transpose(a) gives the matrix transpose.
  • If we are not providing axes argument value, then the dimensions simply reversed.
  • In transpose() operation, just dimensions will be interchanged, but not content.
    Hence it is not required to create new array and it returns view of the existing
    array.

eg: shapes in the dimension

  • (2,3)—>(3,2)
  • (2,3,4)–>(4,3,2),(2,4,3),(3,2,4),(3,4,2)

A\;=\;\begin{bmatrix}1&2\\3&4\end{bmatrix}\;\;A^{T\;}=\;\begin{bmatrix}1&3\\2&4\end{bmatrix}

A=[ ] A=[ ]

Example

Python
In [234]:
import numpy as np
a = np.array([[1,2],[3,4]])
atrans = np.transpose(a)
print(f"Original Array : \n {a}")
print(f"Transposed Array : \n {atrans}"

Output

PowerShell
Original Array : 
[[1 2]
[3 4]]
Transposed Array : 
[[1 3]
[2 4]]

Example

Python
In [235]:
import numpy as np
help(np.transpose)

Output

PowerShell
Help on function transpose in module numpy:
transpose(a, axes=None)
 Reverse or permute the axes of an array; returns the modified array.
 
 For an array a with two axes, transpose(a) gives the matrix transpose.

without specifying the ‘axes’ parameter while calling the transpose() function

When we call the transpose() function without specifying the axes parameter then
input dimension will be simply reversed

  • 1-D array (4,) ==> Transposed Array ::(4,) No change
  • 2-D array (2,3) ==> Trasposed Array :: (3,2)
  • 3-D array (2,3,4) ==> Transposed Array :: (4,3,2)
  • 4-D array (2,2,3,4)==> Transposed Array :: (4,3,2,2)