Table of Contents

Copying, Sorting and Reshaping

# import numpy 
import numpy as np

Copy

  • Copies array to new memory

  • Syntax: np.copy(array)

# create an array `A1`
A1 = np.arange(10)
print(A1)
[0 1 2 3 4 5 6 7 8 9]
# copy `A1` into A2 
A2 = np.copy(A1)
print(A2)
[0 1 2 3 4 5 6 7 8 9]

View

  • Creates view of array elements with type(dtype)

  • Syntax: array.view(np.dtype)

# view of array A2 
A3 = A2.view(np.float16)
print(A3)
[0.0e+00 0.0e+00 0.0e+00 0.0e+00 6.0e-08 0.0e+00 0.0e+00 0.0e+00 1.2e-07
 0.0e+00 0.0e+00 0.0e+00 1.8e-07 0.0e+00 0.0e+00 0.0e+00 2.4e-07 0.0e+00
 0.0e+00 0.0e+00 3.0e-07 0.0e+00 0.0e+00 0.0e+00 3.6e-07 0.0e+00 0.0e+00
 0.0e+00 4.2e-07 0.0e+00 0.0e+00 0.0e+00 4.8e-07 0.0e+00 0.0e+00 0.0e+00
 5.4e-07 0.0e+00 0.0e+00 0.0e+00]

Sorting

  • Returns a sorted copy of an array.

  • Syntax: array.sort()

    • element-wise sorting(default)

    • axis = 0; row

    • axis = 1; column Axis

# Unsorted array
A4 = np.array([9, 2, 3,1, 5, 10])
print(A4) 
[ 9  2  3  1  5 10]
# Call sort function
A4.sort()
print(A4)
[ 1  2  3  5  9 10]
# Row and column unsorted
A5 = np.array([[4, 1, 3], [9, 5, 8]])
print(A5) 
[[4 1 3]
 [9 5 8]]
# Apply sort function on column axis=1
A5.sort(axis=1)
print(A5)
[[1 3 4]
 [5 8 9]]

Flatten: Flattens 2D array to 1D array

# 2D array
A6 = np.array([[4, 1, 3], [9, 5, 8]])
# 1D array 
A6.flatten()
array([4, 1, 3, 9, 5, 8])

Transpose: Transposes array (rows become columns and vice versa)

A7 = np.array([[4, 1, 3], [9, 5, 8]])
A7
array([[4, 1, 3],
       [9, 5, 8]])
# Transpose A7 
A7.T
array([[4, 9],
       [1, 5],
       [3, 8]])

Reshape: Reshapes arr to r rows, c columns without changing data

Reshape

A8 = np.array([(8,9,10),(11,12,13)])
A8
array([[ 8,  9, 10],
       [11, 12, 13]])
# Reshape --> 3x4
A8.reshape(3,2)
array([[ 8,  9],
       [10, 11],
       [12, 13]])

Resize: Changes arr shape to rxc and fills new values with 0

A9 = np.array([(8,9,10),(11,12,13)])
A9
array([[ 8,  9, 10],
       [11, 12, 13]])
# Resize 
A9.resize(3, 2)
A9
array([[ 8,  9],
       [10, 11],
       [12, 13]])

References

  • https://numpy.org/

  • https://www.edureka.co/blog/python-numpy-tutorial/

  • https://github.com/enthought/Numpy-Tutorial-SciPyConf-2019

  • Python Machine Learning Cookbook


This notebook was created by Jubayer Hossain | Copyright © 2020, Jubayer Hossain