0% found this document useful (0 votes)
17 views

Numpy - Jupyter Notebook

Uploaded by

Lucas Melo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Numpy - Jupyter Notebook

Uploaded by

Lucas Melo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Python Library – NumPy

NumPy is a general-purpose array-processing Python library which provides handy methods/functions for
working n-dimensional arrays. NumPy is a short form for “Numerical Python“. It provides various
computing tools such as comprehensive mathematical functions, and linear algebra routines.

NumPy developed by Travis Olliphant in 2005.

Install NumPy Library


In [1]: pip install numpy

Requirement already satisfied: numpy in c:\users\user\anaconda3\lib\site-packages (1.2


1.5)
Note: you may need to restart the kernel to use updated packages.

Import NumPy Library


In [2]: import numpy as np

In [3]: a = np.arange(15).reshape(3,5)

a

Out[3]: array([[ 0, 1, 2, 3, 4],


[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])

a.shape (3, 5) a.ndim 2 a.dtype.name 'int64' a.itemsize 8 a.size 15 type(a) <class 'numpy.ndarray'> b =
np.array([6, 7, 8]) b array([6, 7, 8]) type(b) <class 'numpy.ndarray'>

In [4]: # Shape

a.shape

Out[4]: (3, 5)

In [5]: # dimension

a.ndim

Out[5]: 2

In [6]: # data type



a.dtype

Out[6]: dtype('int32')

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [7]: # item size

a.size

Out[7]: 15

In [8]: # type

print(type(a))

<class 'numpy.ndarray'>

Array Creation

In [9]: b = np.array([2,4,6,8])

b

Out[9]: array([2, 4, 6, 8])

In [10]: # Shape, item Size, Data Type, Type



print(f"Shape : {b.shape}")
print(f"Size : {b.size}")
print(f"Data Type : {b.dtype}")
print(f"Type : {type(b)}")

Shape : (4,)
Size : 4
Data Type : int32
Type : <class 'numpy.ndarray'>

In [11]: c = np.array([1.3, 2.5, 3.4, 4.6])



c

Out[11]: array([1.3, 2.5, 3.4, 4.6])

In [12]: # Shape, item Size, Data Type, Type



print(f"Shape : {c.shape}")
print(f"Size : {c.size}")
print(f"Data Type : {c.dtype}")
print(f"Type : {type(c)}")

Shape : (4,)
Size : 4
Data Type : float64
Type : <class 'numpy.ndarray'>

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [13]: # 2 dimension array creation

d = np.array([(1,3,5,7),(2,4,6,8)])

d

Out[13]: array([[1, 3, 5, 7],


[2, 4, 6, 8]])

In [14]: # Shape, item Size, Data Type, Type



print(f"Shape : {d.shape}")
print(f"Size : {d.size}")
print(f"Data Type : {d.dtype}")
print(f"Type : {type(d)}")

Shape : (2, 4)
Size : 8
Data Type : int32
Type : <class 'numpy.ndarray'>

In [15]: # numpy array create with data type



e = np.array([10,20,30,40], dtype=complex)

e

Out[15]: array([10.+0.j, 20.+0.j, 30.+0.j, 40.+0.j])

In [16]: # data type



e.dtype

Out[16]: dtype('complex128')

Zeros, Ones, Empty Arrays

In [17]: ab = np.zeros((3,4))

ab

Out[17]: array([[0., 0., 0., 0.],


[0., 0., 0., 0.],
[0., 0., 0., 0.]])

In [18]: ac = np.ones((2,4))

ac

Out[18]: array([[1., 1., 1., 1.],


[1., 1., 1., 1.]])

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [19]: # data type, shape, size

print(f"Zeros Array\nData Type : {ab.dtype}")
print(f"Item Size : {ab.size}")
print(f"Shape : {ab.shape}\n")
print(f"Ones Array\nData Type : {ac.dtype}")
print(f"Item Size : {ac.size}")
print(f"Shape : {ac.shape}")

Zeros Array
Data Type : float64
Item Size : 12
Shape : (3, 4)

Ones Array
Data Type : float64
Item Size : 8
Shape : (2, 4)

In [20]: one = np.ones((3,3), dtype='int8')


print(f"Ones Array\n\n{one}")
print("\nData Type :", one.dtype)
print("Shape :", one.shape)
print('Size :', one.size)

Ones Array

[[1 1 1]
[1 1 1]
[1 1 1]]

Data Type : int8


Shape : (3, 3)
Size : 9

In [21]: zero = np.zeros((5,5), dtype='int16')



zero[2,2] = 5

print(zero)

[[0 0 0 0 0]
[0 0 0 0 0]
[0 0 5 0 0]
[0 0 0 0 0]
[0 0 0 0 0]]

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [22]: three = np.zeros((3,3))

three[1,1] = 5

inone = np.ones((5,5))

inone[1:-1,1:4] = three

print(f"Zeros with 5 \n\n{three}\n")
print(f"Ones & Zeros with 5 \n\n{inone}")

Zeros with 5

[[0. 0. 0.]
[0. 5. 0.]
[0. 0. 0.]]

Ones & Zeros with 5

[[1. 1. 1. 1. 1.]
[1. 0. 0. 0. 1.]
[1. 0. 5. 0. 1.]
[1. 0. 0. 0. 1.]
[1. 1. 1. 1. 1.]]

In [23]: out = np.zeros((5,5))



inner = np.ones((3,3))

inner[1,1] = 0

out[1:4,1:4] = inner

print(out)

[[0. 0. 0. 0. 0.]
[0. 1. 1. 1. 0.]
[0. 1. 0. 1. 0.]
[0. 1. 1. 1. 0.]
[0. 0. 0. 0. 0.]]

In [24]: inequal = inner



inequal[1,1] = 0

print(inner)

[[1. 1. 1.]
[1. 0. 1.]
[1. 1. 1.]]

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [25]: # copy numpy

onn = np.ones((3,2), dtype='int8')

onc = onn.copy()

onc[1,:] = 0

print('Original - \n', onn)
print('\nCopy - \n', onc)

Original -
[[1 1]
[1 1]
[1 1]]

Copy -
[[1 1]
[0 0]
[1 1]]

In [26]: empty = np.empty((2,3)) #Empty gernerates random numbers



empty

Out[26]: array([[6.23042070e-307, 4.67296746e-307, 1.69121096e-306],


[9.34609111e-307, 1.42413555e-306, 1.78019082e-306]])

In [27]: rang = np.arange(10,50, 10)



rang

Out[27]: array([10, 20, 30, 40])

In [28]: arange = np.arange(5)



arange

Out[28]: array([0, 1, 2, 3, 4])

In [29]: rg = np.random.default_rng(1) # create instance of default random number generator



d_random = rg.random((2,4))

d_random

Out[29]: array([[0.51182162, 0.9504637 , 0.14415961, 0.94864945],


[0.31183145, 0.42332645, 0.82770259, 0.40919914]])

In [30]: d_random = rg.random((3,4))



d_random

Out[30]: array([[0.54959369, 0.02755911, 0.75351311, 0.53814331],


[0.32973172, 0.7884287 , 0.30319483, 0.45349789],
[0.1340417 , 0.40311299, 0.20345524, 0.26231334]])

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [31]: rng_reshape = np.arange(15).reshape(5,3)

rng_reshape

Out[31]: array([[ 0, 1, 2],


[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11],
[12, 13, 14]])

In [32]: abc = np.arange(9).reshape(3,3)



abc

Out[32]: array([[0, 1, 2],


[3, 4, 5],
[6, 7, 8]])

In [33]: # Sum of each column



abc.sum(axis=0)

Out[33]: array([ 9, 12, 15])

In [34]: # Sum of each row



abc.sum(axis=1)

Out[34]: array([ 3, 12, 21])

In [35]: # Shape, item Size, Data Type, Type



print(f"Shape : {rang.shape}")
print(f"Size : {rang.size}")
print(f"Data Type : {rang.dtype}")
print(f"Type : {type(rang)}")

Shape : (4,)
Size : 4
Data Type : int32
Type : <class 'numpy.ndarray'>

Numpy Zeros Like

In [36]: x_like = np.arange(9).reshape(3,3)



x_like

Out[36]: array([[0, 1, 2],


[3, 4, 5],
[6, 7, 8]])

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [37]: zeros_like = np.zeros_like(x_like)

zeros_like

Out[37]: array([[0, 0, 0],


[0, 0, 0],
[0, 0, 0]])

Numpy Ones Like

In [38]: ones_like = np.ones_like(zeros_like)



ones_like

Out[38]: array([[1, 1, 1],


[1, 1, 1],
[1, 1, 1]])

Numpy Full Like

In [39]: full_like = np.full_like(ones_like, 7) # Full Like with Array Value



full_like

Out[39]: array([[7, 7, 7],


[7, 7, 7],
[7, 7, 7]])

In [40]: ones_like = np.ones_like(zeros_like, order='C')



ones_like

Out[40]: array([[1, 1, 1],


[1, 1, 1],
[1, 1, 1]])

In [41]: from numpy import pi

In [42]: ln = np.linspace(2,4,5) # 5 numbers from 2 to 4



print(ln)

[2. 2.5 3. 3.5 4. ]

In [43]: li_pi = np.linspace(0, 2 * pi, 12)



fx = np.sin(li_pi)

fx

Out[43]: array([ 0.00000000e+00, 5.40640817e-01, 9.09631995e-01, 9.89821442e-01,


7.55749574e-01, 2.81732557e-01, -2.81732557e-01, -7.55749574e-01,
-9.89821442e-01, -9.09631995e-01, -5.40640817e-01, -2.44929360e-16])

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
Basic Operations

In [44]: a = np.array([10,20,30,40])

b = np.arange(4)

add = a + b
sub = a - b # Subtraction (a-b)
mul = a * b

print(f"Array A : {a}\nArray B : {b}\n")
print(f"Addition (a+b)\n{add}\n")
print(f"Subtraction (a-b)\n{sub}\n")
print(f"Multiplication (a*b)\n{mul}\n")

Array A : [10 20 30 40]


Array B : [0 1 2 3]

Addition (a+b)
[10 21 32 43]

Subtraction (a-b)
[10 19 28 37]

Multiplication (a*b)
[ 0 20 60 120]

In [45]: # a array square



a_2 = a ** 2

a_2

Out[45]: array([ 100, 400, 900, 1600], dtype=int32)

In [46]: # check values True or False



a_2 < 500

Out[46]: array([ True, True, False, False])

In [47]: a = np.array([[1,1],
[0,1]])

b = np.array([[2,0],
[3,4]])
a * b # elementwise product

Out[47]: array([[2, 0],


[0, 4]])

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [48]: # matrix product

a @ b

Out[48]: array([[5, 4],


[3, 4]])

In [49]: a.dot(b) # another matrix product

Out[49]: array([[5, 4],


[3, 4]])

In [50]: rg = np.random.default_rng(1) # create instance of default random number generator


a = np.ones((2, 3), dtype=int)
b = rg.random((2, 3))
a *= 3
a

Out[50]: array([[3, 3, 3],


[3, 3, 3]])

In [51]: b += a
b

Out[51]: array([[3.51182162, 3.9504637 , 3.14415961],


[3.94864945, 3.31183145, 3.42332645]])

In [52]: a += b # b is not automatically converted to integer type



a

---------------------------------------------------------------------------
UFuncTypeError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_10432\1729391664.py in <module>
----> 1 a += b # b is not automatically converted to integer type
2
3 a

UFuncTypeError: Cannot cast ufunc 'add' output from dtype('float64') to dtype('int32')


with casting rule 'same_kind'

In [53]: a = np.array([10,15,20,25,30])

a.sum()

Out[53]: 100

In [54]: a.min()

Out[54]: 10

In [55]: a.max()

Out[55]: 30

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [56]: b = np.arange(12).reshape(3, 4)

b

Out[56]: array([[ 0, 1, 2, 3],


[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])

In [57]: b.sum(axis=0) # sum of each column

Out[57]: array([12, 15, 18, 21])

In [58]: b.sum(axis=1) # sum of each row

Out[58]: array([ 6, 22, 38])

In [59]: b.min(axis=0) # min of each column

Out[59]: array([0, 1, 2, 3])

In [60]: b.min(axis=1) # min of each row

Out[60]: array([0, 4, 8])

In [61]: b.max(axis=0) # max of each column

Out[61]: array([ 8, 9, 10, 11])

In [62]: b.max(axis=1) # max of each row

Out[62]: array([ 3, 7, 11])

In [63]: b.cumsum(axis=0) # cumulative sum along each column

Out[63]: array([[ 0, 1, 2, 3],


[ 4, 6, 8, 10],
[12, 15, 18, 21]], dtype=int32)

In [64]: b.cumsum(axis=1) # cumulative sum along each row

Out[64]: array([[ 0, 1, 3, 6],


[ 4, 9, 15, 22],
[ 8, 17, 27, 38]], dtype=int32)

Universal Function

In [65]: a = np.array([10,20,30])

np.exp(a)

Out[65]: array([2.20264658e+04, 4.85165195e+08, 1.06864746e+13])

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [66]: np.sqrt(81)

Out[66]: 9.0

In [67]: b = np.array([4,9,16,25])

x = np.sqrt(b)

x

Out[67]: array([2., 3., 4., 5.])

In [68]: y = np.array([1.,-2.,3.,-3.])

np.add(x, y)

Out[68]: array([3., 1., 7., 2.])

Array Indexing / Slicing


In [69]: a = np.array([2,4,6,8]) # 1D array

print(a)
print(a.shape)

[2 4 6 8]
(4,)

In [70]: a[:2] # print first two elements

Out[70]: array([2, 4])

In [71]: a[-1] # print last one elements

Out[71]: 8

In [72]: b = np.array([[1,2,3,4],[5,6,7,8]]) # 2D array



print(b)
print(b.shape)

[[1 2 3 4]
[5 6 7 8]]
(2, 4)

In [73]: b[0][:2] # print first two elements of first row

Out[73]: array([1, 2])

In [74]: b[1, :2] # print first two elements of second row

Out[74]: array([5, 6])

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [75]: b[1, 2] # print 7

Out[75]: 7

In [76]: c = np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]]) # 3D array



print(c)
print(c.shape)

[[[ 1 2 3]
[ 4 5 6]]

[[ 7 8 9]
[10 11 12]]]
(2, 2, 3)

In [77]: c[0]

Out[77]: array([[1, 2, 3],


[4, 5, 6]])

In [78]: c[1]

Out[78]: array([[ 7, 8, 9],


[10, 11, 12]])

In [79]: c[0,0]

Out[79]: array([1, 2, 3])

In [80]: c[1,0]

Out[80]: array([7, 8, 9])

In [81]: c[0, 1, -1]

Out[81]: 6

In [82]: c[:, 1, 0]

Out[82]: array([ 4, 10])

In [83]: c[1, :, -1]

Out[83]: array([ 9, 12])

NumPy Data Types


In [84]: a = np.array(['Data Science', 'Machine Learning', 'Deep Learning', 'AI' ])

print(a)
print(a.dtype)

['Data Science' 'Machine Learning' 'Deep Learning' 'AI']


<U16
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [85]: a.dtype

Out[85]: dtype('<U16')

In [86]: b = np.array([100,200,300])

b.dtype

Out[86]: dtype('int32')

In [87]: c = np.array([2.05, 3.0, 4.01, 5.6])



c.dtype

Out[87]: dtype('float64')

In [88]: d = np.array([True, True, False, True])



d.dtype

Out[88]: dtype('bool')

In [89]: e = np.array([1.0 + 2.0j, 1.5 + 2.5j])



e.dtype

Out[89]: dtype('complex128')

Numpy Copy / View

The copy owns the data and any changes made to the copy will not affect original array, and any changes
made to the original array will not affect the copy.

The view does not own the data and any changes made to the view will affect the original array, and any
changes made to the original array will affect the view.

In [90]: a = np.array([1,2,3,4,5])

x = a.copy()

a[1] = 10

print(a)
print(x)

[ 1 10 3 4 5]
[1 2 3 4 5]

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [91]: a = np.array([1,2,3,4,5])

x = a.copy()

x[1] = 7

print(a)
print(x)

[1 2 3 4 5]
[1 7 3 4 5]

In [92]: a = np.array([1,2,3,4,5])

x = a.view()

a[1] = 10

print(a)
print(x)

[ 1 10 3 4 5]
[ 1 10 3 4 5]

In [93]: a = np.array([1,2,3,4,5])

x = a.view()

x[-1] = 20

print(a)
print(x)

[ 1 2 3 4 20]
[ 1 2 3 4 20]

Reshape NumPy Array

In [94]: a = np.arange((12))

a

Out[94]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])

In [95]: a2 = a.reshape(4,3) # Reshape 1D array to 2D array



a2

Out[95]: array([[ 0, 1, 2],


[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [96]: a3 = a.reshape(2,3,2) # Reshape 1D to 3D array

a3

Out[96]: array([[[ 0, 1],


[ 2, 3],
[ 4, 5]],

[[ 6, 7],
[ 8, 9],
[10, 11]]])

In [97]: print(f"a Shape: {a.shape}")


print(f"a2 Shape: {a2.shape}")
print(f"a3 Shape: {a3.shape}")

a Shape: (12,)
a2 Shape: (4, 3)
a3 Shape: (2, 3, 2)

NumPy Array Iterating

In [98]: for i in a:
print(i)

0
1
2
3
4
5
6
7
8
9
10
11

In [99]: for x in a2:


print(x)

[0 1 2]
[3 4 5]
[6 7 8]
[ 9 10 11]

In [100]: for y in a3:


print(y)

[[0 1]
[2 3]
[4 5]]
[[ 6 7]
[ 8 9]
[10 11]]

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
NumPy Array Join

In [101]: a = np.array([1,2,3])

b = np.array([4,5,6])

ab = np.concatenate((a, b))

ab

Out[101]: array([1, 2, 3, 4, 5, 6])

In [102]: a = np.array([[1,2],[3,4]])

b = np.array([[5,6],[7,8]])

ab = np.concatenate((a, b))

ab

Out[102]: array([[1, 2],


[3, 4],
[5, 6],
[7, 8]])

In [103]: a = np.array([[1,2],[3,4]])

b = np.array([[5,6],[7,8]])

ab = np.concatenate((a, b), axis=1)

ab

Out[103]: array([[1, 2, 5, 6],


[3, 4, 7, 8]])

In [104]: # Stack Function



a = np.array([1, 2, 3])

b = np.array([4, 5, 6])

ab = np.stack((a,b), axis=1)

ab

Out[104]: array([[1, 4],


[2, 5],
[3, 6]])

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [105]: a = np.array([1, 2, 3])

b = np.array([4, 5, 6])

ab = np.hstack((a,b))

ab

Out[105]: array([1, 2, 3, 4, 5, 6])

In [106]: a = np.array([[1,2],[3,4]])

b = np.array([[5,6],[7,8]])

ab = np.hstack((a, b))

ab

Out[106]: array([[1, 2, 5, 6],


[3, 4, 7, 8]])

In [107]: a = np.array([1, 2, 3])



b = np.array([4, 5, 6])

ab = np.vstack((a,b))

ab

Out[107]: array([[1, 2, 3],


[4, 5, 6]])

In [108]: a = np.array([1, 2, 3])



b = np.array([4, 5, 6])

ab = np.dstack((a,b))

ab

Out[108]: array([[[1, 4],


[2, 5],
[3, 6]]])

NumPy Array Split

In [109]: a = np.array([1, 2, 3, 4, 5, 6])



ab = np.array_split(a, 2)

ab

Out[109]: [array([1, 2, 3]), array([4, 5, 6])]

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [110]: a = np.array([1, 2, 3, 4, 5, 6])

ab = np.array_split(a, 3)

ab

Out[110]: [array([1, 2]), array([3, 4]), array([5, 6])]

In [111]: a = np.array([1, 2, 3, 4, 5, 6])



ab = np.array_split(a, 4)

ab

Out[111]: [array([1, 2]), array([3, 4]), array([5]), array([6])]

Split Into Arrays

In [112]: ab[0]

Out[112]: array([1, 2])

In [113]: ab[1]

Out[113]: array([3, 4])

In [114]: ab[2]

Out[114]: array([5])

In [115]: ab[3]

Out[115]: array([6])

2D Arrays Split

In [116]: a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18]]

ab = np.array_split(a, 2)

ab

Out[116]: [array([[1, 2, 3],


[4, 5, 6],
[7, 8, 9]]),
array([[10, 11, 12],
[13, 14, 15],
[16, 17, 18]])]

In [117]: ab[0]

Out[117]: array([[1, 2, 3],


[4, 5, 6],
[7, 8, 9]])
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [118]: ab[1]

Out[118]: array([[10, 11, 12],


[13, 14, 15],
[16, 17, 18]])

In [119]: a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18]]

ab = np.array_split(a, 3)

ab

Out[119]: [array([[1, 2, 3],


[4, 5, 6]]),
array([[ 7, 8, 9],
[10, 11, 12]]),
array([[13, 14, 15],
[16, 17, 18]])]

In [120]: ab[0]

Out[120]: array([[1, 2, 3],


[4, 5, 6]])

In [121]: ab[1]

Out[121]: array([[ 7, 8, 9],


[10, 11, 12]])

In [122]: ab[2]

Out[122]: array([[13, 14, 15],


[16, 17, 18]])

In [123]: a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])

ab = np.array_split(a, 4)

ab

Out[123]: [array([[1, 2, 3]]),


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

In [124]: ab[0]

Out[124]: array([[1, 2, 3]])

In [125]: ab[1]

Out[125]: array([[4, 5, 6]])

In [126]: ab[2]

Out[126]: array([[7, 8, 9]])


Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [127]: a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18]]

ab = np.hsplit(a, 3)

ab

Out[127]: [array([[ 1],


[ 4],
[ 7],
[10],
[13],
[16]]),
array([[ 2],
[ 5],
[ 8],
[11],
[14],
[17]]),
array([[ 3],
[ 6],
[ 9],
[12],
[15],
[18]])]

In [128]: a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])



ab = np.hsplit(a, 3)

ab

Out[128]: [array([[1],
[4],
[7]]),
array([[2],
[5],
[8]]),
array([[3],
[6],
[9]])]

In [129]: a = np.array([[1,2],[3,4],[5,6]])

ab = np.hsplit(a, 2)

ab

Out[129]: [array([[1],
[3],
[5]]),
array([[2],
[4],
[6]])]

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [130]: a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])

ab = np.where(a == 5)

ab

Out[130]: (array([4], dtype=int64),)

In [131]: a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])



ab = np.where(a == 8)

ab

Out[131]: (array([7], dtype=int64),)

In [132]: a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])



ab = np.where(a%2 == 0)

ab

Out[132]: (array([1, 3, 5, 7], dtype=int64),)

In [133]: a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])



ab = np.where(a%2 == 1)

ab

Out[133]: (array([ 0, 2, 4, 6, 8, 10, 12], dtype=int64),)

In [134]: a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])



ab = np.searchsorted(a, 3)

ab

Out[134]: 2

In [135]: a = np.array([6, 7, 8, 9, 10, 11, 12, 13])



ab = np.searchsorted(a, 12, side='right')

ab

Out[135]: 7

In [136]: a = np.array([6, 7, 8, 9, 10, 11, 12, 13])



ab = np.searchsorted(a, 12)

ab

Out[136]: 6

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [137]: a = np.array([6, 7, 8, 9, 10, 11, 12, 13])

ab = np.searchsorted(a, [1,3,8,9,10])

ab

Out[137]: array([0, 0, 2, 3, 4], dtype=int64)

NumPy Array Sort

In [138]: a = np.array([14, 1, 11, 3, 6, 4, 7, 12, 13, 8, 15, 9, 10, 0, 2, 5])



np.sort(a)

Out[138]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])

In [139]: a = np.array(['Cat', 'Zoo', 'Football', 'Dog', 'Eye', 'Apple'])



np.sort(a)

Out[139]: array(['Apple', 'Cat', 'Dog', 'Eye', 'Football', 'Zoo'], dtype='<U8')

In [140]: a = np.array([False, True, False, False, True, False])



np.sort(a)

Out[140]: array([False, False, False, False, True, True])

In [141]: a2 = np.array([[3, 2, 4], [5, 0, 1]])



np.sort(a2)

Out[141]: array([[2, 3, 4],


[0, 1, 5]])

In [142]: arr = np.array([41, 42, 43, 44])



# Create an empty list
filter_arr = []

# go through each element in arr
for element in arr:
# if the element is higher than 42, set the value to True, otherwise False:
if element > 42:
filter_arr.append(True)
else:
filter_arr.append(False)

newarr = arr[filter_arr]

print(filter_arr)
print(newarr)

[False, False, True, True]


[43 44]

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [143]: arr = np.array([1, 2, 3, 4, 5, 6, 7])

# Create an empty list
filter_arr = []

# go through each element in arr
for element in arr:
# if the element is completely divisble by 2, set the value to True, otherwise False
if element % 2 == 0:
filter_arr.append(True)
else:
filter_arr.append(False)

newarr = arr[filter_arr]

print(filter_arr)
print(newarr)

[False, True, False, True, False, True, False]


[2 4 6]

In [144]: arr = np.array([1, 2, 3, 4, 5, 6, 7])



# Create an empty list
filter_arr = []

# go through each element in arr
for element in arr:
# if the element is not completely divisble by 2, set the value to True, otherwise Fals
if element % 2 == 1:
filter_arr.append(True)
else:
filter_arr.append(False)

newarr = arr[filter_arr]

print(filter_arr)
print(newarr)

[True, False, True, False, True, False, True]


[1 3 5 7]

In [145]: ax = np.array([10, 20, 30, 40, 50])



filter_arr = ax > 20

new_ax = ax[filter_arr]

print(filter_arr)
print(new_ax)

[False False True True True]


[30 40 50]

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
Random Numbers in NumPy

In [146]: # import library



from numpy import random

In [147]: x = random.randint(100)

print(x)

39

In [148]: x = random.rand()

x

Out[148]: 0.33150184362238155

In [149]: # Generate a 1-D array containing 5 random integers from 0 to 100:



x = random.randint(100, size=(3))

print(x)

[92 25 61]

In [150]: # Generate a 2-D array with 2 rows, each row containing 3 random integers from 0 to 100:

x = random.randint(100, size=(2,3))

x

Out[150]: array([[43, 87, 7],


[77, 62, 90]])

In [151]: # Generate a 1-D array containing 5 random floats:



x = random.rand(5)

print(x)

[0.2283375 0.79971818 0.32832239 0.54718548 0.0303609 ]

In [152]: # Generate a 2-D array with 3 rows, each row containing 2 random numbers:

x = random.rand(3, 2)

print(x)

[[0.94764137 0.43819239]
[0.52815542 0.01067087]
[0.72109457 0.10579046]]

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [153]: # Return one of the values in an array:

x = random.choice([3, 5, 7, 9])

print(x)

In [154]: # The choice() method also allows you to return an array of values.
# Add a size parameter to specify the shape of the array.

x = random.choice([3, 5, 7, 9], size=(3, 5))

print(x)

[[9 7 5 7 3]
[5 5 7 7 5]
[3 3 5 3 5]]

Random Data Distribution

What is Data Distribution?

Data Distribution is a list of all possible values, and how often each value occurs. Such lists are important
when working with statistics and data science. The random module offer methods that returns randomly
generated data distributions.

ExampleGet your own Python Server Generate a 1-D array containing 100 values, where each value
has to be 3, 5, 7 or 9.

The probability for the value to be 3 is set to be 0.1

The probability for the value to be 5 is set to be 0.3

The probability for the value to be 7 is set to be 0.6

The probability for the value to be 9 is set to be 0

In [155]: x = random.choice([3, 5, 7, 9], p=[0.1, 0.3, 0.6, 0.0], size=(100))



print(x)

[5 7 3 7 7 7 3 7 7 7 7 7 7 5 7 3 7 7 5 7 5 5 7 3 7 7 5 7 7 7 7 7 5 7 5 7 7
7 7 7 7 7 7 7 7 7 7 5 5 5 5 5 7 7 7 7 7 5 7 3 3 7 5 5 7 7 7 5 5 5 5 5 5 5
7 7 5 7 7 5 5 7 5 7 7 5 7 7 7 7 7 7 7 7 5 7 3 5 5 7]

In [156]: # Same example as above, but return a 2-D array with 3 rows, each containing 5 values.

x = random.choice([3, 5, 7, 9], p=[0.1, 0.3, 0.6, 0.0], size=(3, 5))

print(x)

[[7 7 5 5 3]
[5 5 7 7 3]
[7 5 7 7 3]]
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
Random Permutations of Elements

Shuffling Arrays

In [157]: arr = np.array([1, 2, 3, 4, 5])



random.shuffle(arr) # The shuffle() method makes changes to the original array.

print(arr)

[1 2 4 3 5]

In [158]: # Generating Permutation of Arrays



arr = np.array([1, 2, 3, 4, 5])

print(random.permutation(arr)) # The permutation() method returns a re-arranged array (an

[1 5 4 2 3]

Normal (Gaussian) Distribution

In [159]: x = random.normal(size=(2, 3))



print(x)

[[-1.40144554 -1.35534505 0.4355295 ]


[ 1.34332605 0.70828922 -0.80585434]]

In [160]: # Generate a random normal distribution of size 2x3 with mean at 3 and standard deviation

x = random.normal(loc=3, scale=2, size=(2, 3))

print(x)

[[2.82806795 3.83998103 3.76165957]


[0.93354518 3.08895529 1.73914323]]

Visualization of Normal Distribution

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [161]: import matplotlib.pyplot as plt
import seaborn as sns

sns.distplot(random.normal(size=1000), hist=False)

plt.show()

C:\Users\User\anaconda3\lib\site-packages\seaborn\distributions.py:2619: FutureWarning:
`distplot` is a deprecated function and will be removed in a future version. Please ada
pt your code to use either `displot` (a figure-level function with similar flexibility)
or `kdeplot` (an axes-level function for kernel density plots).
warnings.warn(msg, FutureWarning)

Binomial Distribution

In [162]: x = random.binomial(n=20, p=0.5, size=10)



print(x)

[ 8 11 7 9 11 11 11 14 7 7]

Chi Square Distribution

In [163]: x = random.chisquare(df=2, size=(2, 3))



print(x)

[[0.74806038 1.03024374 2.75760522]


[0.33185553 0.10245362 0.27963136]]

Visualization of Chi Square Distribution


Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [164]: from numpy import random
import matplotlib.pyplot as plt
import seaborn as sns

sns.distplot(random.chisquare(df=1, size=1000), hist=False)

plt.show()

C:\Users\User\anaconda3\lib\site-packages\seaborn\distributions.py:2619: FutureWarning:
`distplot` is a deprecated function and will be removed in a future version. Please ada
pt your code to use either `displot` (a figure-level function with similar flexibility)
or `kdeplot` (an axes-level function for kernel density plots).
warnings.warn(msg, FutureWarning)

Visualization of Poisson Distribution

Poisson Distribution has two parameters:

1. lam - rate or known number of occurrences e.g. 2 for above problem.


2. size - The shape of the returned array.

In [165]: x = random.poisson(lam=2, size=10)



print(x)

[0 2 1 1 1 1 2 0 3 2]

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [166]: from numpy import random
import matplotlib.pyplot as plt
import seaborn as sns

sns.distplot(random.poisson(lam=2, size=1000), kde=False)

plt.show()

C:\Users\User\anaconda3\lib\site-packages\seaborn\distributions.py:2619: FutureWarning:
`distplot` is a deprecated function and will be removed in a future version. Please ada
pt your code to use either `displot` (a figure-level function with similar flexibility)
or `histplot` (an axes-level function for histograms).
warnings.warn(msg, FutureWarning)

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [167]: from numpy import random
import matplotlib.pyplot as plt
import seaborn as sns

sns.distplot(random.poisson(lam=3, size=1000))

plt.show()

Uniform Distribution

Uniform Distribution has three parameters:

1. a - lower bound - default 0 .0.


2. b - upper bound - default 1.0.
3. size - The shape of the returned array.

In [168]: x = random.uniform(size=(2, 3))



print(x)

[[0.82751804 0.00422504 0.97971968]


[0.12829234 0.24044758 0.90011081]]

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
Visualization of Uniform Distribution

In [169]: from numpy import random


import matplotlib.pyplot as plt
import seaborn as sns

sns.distplot(random.uniform(size=1000), hist=False)

plt.show()

C:\Users\User\anaconda3\lib\site-packages\seaborn\distributions.py:2619: FutureWarning:
`distplot` is a deprecated function and will be removed in a future version. Please ada
pt your code to use either `displot` (a figure-level function with similar flexibility)
or `kdeplot` (an axes-level function for kernel density plots).
warnings.warn(msg, FutureWarning)

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [170]: sns.distplot(random.uniform(size=30), hist=False)

plt.show()

C:\Users\User\anaconda3\lib\site-packages\seaborn\distributions.py:2619: FutureWarning:
`distplot` is a deprecated function and will be removed in a future version. Please ada
pt your code to use either `displot` (a figure-level function with similar flexibility)
or `kdeplot` (an axes-level function for kernel density plots).
warnings.warn(msg, FutureWarning)

NumPy ufuncs
In [171]: x = [1, 2, 3, 4]
y = [4, 5, 6, 7]
z = []

for i, j in zip(x, y):
z.append(i + j)
print(z)

[5, 7, 9, 11]

In [172]: x = [1, 2, 3, 4]
y = [4, 5, 6, 7]

z = np.add(x, y) # add() function

print(z)

[ 5 7 9 11]

The frompyfunc() method takes the following arguments:


Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
1. function - the name of the function.
2. inputs - the number of input arguments (arrays).
3. outputs - the number of output arrays.

In [173]: def myadd(x, y):


return x+y

myadd = np.frompyfunc(myadd, 2, 1)

print(myadd([1, 2, 3, 4], [5, 6, 7, 8]))

[6 8 10 12]

In [174]: myadd([1, 2, 3, 4], [10,20,30,40])

Out[174]: array([11, 22, 33, 44], dtype=object)

Check if a Function is a ufunc

In [175]: print(type(np.add))

<class 'numpy.ufunc'>

In [176]: print(type(np.concatenate))

<class 'function'>

In [177]: if type(np.add) == np.ufunc:


print('add is ufunc')
else:
print('add is not ufunc')

add is ufunc

In [178]: try:
if type(np.blahblah) == np.ufunc:
print('blahblah is ufunc')
else:
print('blahblah is not ufunc')
except:
print('blahblah is not ufunc in NumPy.')

blahblah is not ufunc in NumPy.

NumPy Arithmetic

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [179]: a = np.array([10,20,30,40])

b = np.array([100,200,300,400])

add = np.add(a, b)

print(add)

[110 220 330 440]

In [180]: a = np.array([10,20,30,40])

b = np.array([100,200,300,400])

subtract = np.subtract(b, a)

print(subtract)

[ 90 180 270 360]

In [181]: a = np.array([10,20,30,40])

b = np.array([100,200,300,400])

multiply = np.multiply(a, b)

print(multiply)

[ 1000 4000 9000 16000]

In [182]: a = np.array([10,20,30,40])

b = np.array([100,200,300,400])

divide = np.divide(b, a)

print(divide)

[10. 10. 10. 10.]

In [183]: a = np.array([10,20,30,40])

b = np.array([1,2,3,4])

power = np.power(a, b)

print(power)

[ 10 400 27000 2560000]

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [184]: a = np.array([10,20,30,40])

b = np.array([3,4,6,7])

mod = np.mod(a, b)

print(mod)

[1 0 0 5]

In [185]: a = np.array([10,20,30,40])

b = np.array([3,4,6,7])

remainder = np.remainder(a, b)

print(remainder)

[1 0 0 5]

NumPy Rounding Decimals


In [186]: ab = np.trunc([-3.1666, 3.6667])

print(ab)

[-3. 3.]

In [187]: ab = np.fix([-3.1666, 3.6667])



print(ab)

[-3. 3.]

In [188]: ab = np.around([-3.1666, 3.6667])



print(ab)

[-3. 4.]

In [189]: ab = np.floor([-3.1666, 3.6667])



print(ab)

[-4. 3.]

In [190]: ab = np.ceil([-3.1666, 3.6667])



print(ab)

[-3. 4.]

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
NumPy Logs
In [191]: import numpy as np

ab = np.arange(1, 6)

log2 = np.log2(ab)

print(log2)

[0. 1. 1.5849625 2. 2.32192809]

In [192]: ab = np.arange(1, 6)

log10 = np.log10(ab)

print(log10)

[0. 0.30103 0.47712125 0.60205999 0.69897 ]

Natural Log, or Log at Base e

In [193]: ab = np.arange(1, 6)

log = np.log(ab)

print(log)

[0. 0.69314718 1.09861229 1.38629436 1.60943791]

Log at Any Base

NumPy does not provide any function to take log at any base, so we can use the frompyfunc() function
along with inbuilt function math.log() with two input parameters and one output parameter

In [194]: from math import log


import numpy as np

nplog = np.frompyfunc(log, 2, 1)

print(nplog(100, 15))

1.7005483074552052

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
NumPy Products

In [195]: a = np.array([1, 2, 3, 4])



x = np.prod(a) # 1*2*3*4 = 24

print(x)

24

In [196]: a = np.array([1, 2, 3, 4])



b = np.array([5, 6, 7, 8])

x = np.prod([a , b])

print(x)

40320

In [197]: a = np.array([1, 2, 3, 4])



b = np.array([5, 6, 7, 8])

x = np.prod([a , b], axis=1) # each row

print(x)

[ 24 1680]

In [198]: a = np.array([1, 2, 3, 4])



b = np.array([5, 6, 7, 8])

x = np.prod([a , b], axis=0) # each column

print(x)

[ 5 12 21 32]

In [199]: a = np.array([2, 3, 4, 5])



x = np.cumprod(a)


print(x)

[ 2 6 24 120]

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [200]: a = np.array([1, 2, 3, 4])

b = np.array([5, 6, 7, 8])

x = np.cumprod([a , b])


print(x)

[ 1 2 6 24 120 720 5040 40320]

In [201]: a = np.array([1, 2, 3, 4])



b = np.array([5, 6, 7, 8])

x = np.cumprod([a , b], axis=1)

print(x)

[[ 1 2 6 24]
[ 5 30 210 1680]]

In [202]: a = np.array([1, 2, 3, 4])



b = np.array([5, 6, 7, 8])

c = np.array([9, 10, 11, 12])

x = np.cumprod([a , b, c], axis=0)

print(x)

[[ 1 2 3 4]
[ 5 12 21 32]
[ 45 120 231 384]]

NumPy Differences

E.g. for [1, 2, 3, 4], the discrete difference would be [2-1, 3-2, 4-3] = [1, 1, 1]

In [203]: a = np.array([10, 15, 25, 5])



diff = np.diff(a)

print(diff)

[ 5 10 -20]

We can perform this operation repeatedly by giving parameter n.

E.g. for [1, 2, 3, 4], the discrete difference with n = 2 would be [2-1, 3-2, 4-3] = [1, 1, 1] , then, since n=2, we
will do it once more, with the new result: [1-1, 1-1] = [0, 0]

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [204]: ​
a = np.array([10, 15, 25, 5])

diff = np.diff(a, n=2)

print(diff)

[ 5 -30]

In [205]: a = np.array([1, 2, 3, 4])



diff = np.diff(a , n=2)

print(diff)

[0 0]

NumPy LCM Lowest Common Multiple

The Lowest Common Multiple is the smallest number that is a common multiple of two numbers.

In [206]: num1 = 4
num2 = 6

x = np.lcm(num1, num2)

print(x)

12

The reduce() method will use the ufunc, in this case the lcm() function, on each element, and reduce the
array by one dimension.

In [207]: a = np.array([3, 6, 9])



x = np.lcm.reduce(a)

print(x)

18

Returns: 18 because that is the lowest common multiple of all three numbers (36=18, 63=18 and 9*2=18).

NumPy GCD Greatest Common Denominator

In [208]: num1 = 6
num2 = 9

x = np.gcd(num1, num2)

print(x)

3
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
Returns: 3 because that is the highest number both numbers can be divided by (6/3=2 and 9/3=3).

The reduce() method will use the ufunc, in this case the gcd() function, on each element, and reduce the
array by one dimension.

In [209]: a = np.array([20, 8, 32, 36, 16])



x = np.gcd.reduce(a)

print(x)

Returns: 4 because that is the highest number all values can be divided by.

NumPy Trigonometric Functions

NumPy provides the ufuncs sin(), cos() and tan() that take values in radians and produce the
corresponding sin, cos and tan values.

In [210]: x = np.sin(np.pi/2)

print(x)

1.0

In [211]: pi2 = np.array([np.pi/2, np.pi/3, np.pi/4, np.pi/5])



x = np.sin(pi2)

print(x)

[1. 0.8660254 0.70710678 0.58778525]

In [212]: # Convert Degrees Into Radians



a = np.array([90, 180, 270, 360])

x = np.deg2rad(a)

print(x)

[1.57079633 3.14159265 4.71238898 6.28318531]

In [213]: # Radians to Degrees



a = np.array([90, 180, 270, 360])

x = np.rad2deg(a)

print(x)

[ 5156.62015618 10313.24031235 15469.86046853 20626.48062471]


Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
NumPy provides ufuncs arcsin(), arccos() and arctan() that produce radian values for corresponding sin,
cos and tan values given.

In [214]: x = np.arcsin(1.0)

print(x)

1.5707963267948966

In [215]: a = np.array([1, -1, 0.1])



x = np.arccos(a)

print(x)

[0. 3.14159265 1.47062891]

In [216]: a = np.array([1, -1, 0.1])



x = np.arctan(a)

print(x)

[ 0.78539816 -0.78539816 0.09966865]

In [217]: # Hypotenues

base = 3

perp = 4

x = np.hypot(base, perp)

print(x)

5.0

NumPy Hyperbolic Functions

NumPy provides the ufuncs sinh(), cosh() and tanh() that take values in radians and produce the
corresponding sinh, cosh and tanh values.

In [218]: x = np.sinh(np.pi/2)

x

Out[218]: 2.3012989023072947

In [219]: x = np.cosh(np.pi/2)

x

Out[219]: 2.5091784786580567

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [220]: x = np.tanh(np.pi/2)

x

Out[220]: 0.9171523356672744

Finding Angles

Numpy provides ufuncs arcsinh(), arccosh() and arctanh() that produce radian values for corresponding
sinh, cosh and tanh values given.

In [221]: x = np.arcsinh(1.0)

print(x)

0.881373587019543

NumPy Set Operations

In [222]: ab = np.array([1, 1, 1, 2, 3, 4, 5, 5, 6, 7])



x = np.unique(ab)

print(x)

[1 2 3 4 5 6 7]

In [223]: # Finding Union



a = np.array([1, 2, 3, 4])
b = np.array([3, 4, 5, 6])

x = np.union1d(a, b)

print(x)

[1 2 3 4 5 6]

In [224]: # Finding Union



a = np.array([1, 2, 3, 4])
b = np.array([3, 4, 5, 6])

x = np.intersect1d(a, b, assume_unique=True)

print(x)

[3 4]

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [225]: a = np.array([1, 2, 3, 4])
b = np.array([3, 4, 5, 6])

x = np.setdiff1d(a, b, assume_unique=True)

print(x)

[1 2]

In [226]: a = np.array([1, 2, 3, 4])


b = np.array([3, 4, 5, 6])

x = np.setxor1d(a, b, assume_unique=True)

print(x)

[1 2 5 6]

Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js

You might also like