NumPy CheatSheet

NumPy stands for Numerical Python

Aditri Srivastava
CodeX
4 min readDec 30, 2020

--

NumPy is a Python library for scientific computing. It is a powerful mathematical library that is used for array computing. It is an open-source project and you can use it freely.

Installing NumPy

pip install numpy

Writing this statement in command prompt installs numpy in the system. For more guidance refer to the following official guide.

Importing NumPy

In [1]: import numpy as np

We can import by executing this statement. For our simplicity, we use np as an abbreviation as it is shorter and convenient to use.

NumPy VS Python Lists

In Python, we have ‘lists’ as arrays, but they are slow to process. NumPy aims to provide an array object i.e ndarray which is up to 50x faster than traditional Python lists.

The main reason numpy is faster is that it is stored at one continuous place in memory so that it can be accessed and manipulated easily.

Type and shape of an array

In the following code array declaration, shape and type function can be seen. The ‘shape’ function helps know the number of rows and columns.

In [3]:
b=np.array([[1],[2],[3],[4]])
In [4]:
print(b)
print(type(b))
print(b.shape)
OUTPUT:
[[1] [2] [3] [4]]
<class 'numpy.ndarray'>
(4, 1)

Numpy Arrays Creation

Numpy is very helpful in creating arrays containing only zeros or ones or any constant number. We can also create array containing random numbers using random module.

In [4]:a= np.zeros((3,3))
print(a)
OUTPUT[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
In [5]:b=np.ones((2,3))
print(b)
OUTPUT[[1. 1. 1.]
[1. 1. 1.]]
## Array of some constants
In [6]:
c=np.full((3,2),5)
print(c)
OUTPUT
[[5 5]
[5 5]
[5 5]]
## Identity Matrix
In [7]:
d=np.eye(4)
print(d)
OUTPUT
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]
## Random MatrixIn [8]:e=np.random.random((2,3))
print(e)
### THIS CREATES ARRAY CONTAINING NUMBERS BETWEEN 0 AND 1OUTPUT[[0.53270316 0.92684934 0.78472966]
[0.15786155 0.13987468 0.65476151]]
In [9]:ran=np.random.random((2,3))*100
print(ran)
OUTPUT[[82.53682235 28.72656223 82.94049208]
[ 6.47603388 51.03435714 23.30801068]]

Numpy using a character array

Following code will make you learn all the basics of character array usage of NumPy.

## Character NumpyIn [9]:np.char.add("hi I a","m niice")## ConcatinationOut[9]:array('hi I am niice', dtype='<U13')In [10]:a = "hi it is riya"In [11]:np.char.capitalize(a)
## This capitalizes beginning of sentence.
Out[11]:array('Hi it is riya', dtype='<U13')In [16]:b = "lets say its me"
np.char.join('-',b)
## This method inserts the given character in the given array.
Out[16]:
array('l-e-t-s- -s-a-y- -i-t-s- -m-e', dtype='<U29')In [17]:np.char.title(a)
## This capitalizes beginning of every word.
Out[17]:array('Hi It Is Riya', dtype='<U13')In [18]:m = np.char.upper(a)
## This capitalizes every letter.
In [19]:mOut[19]:array('HI IT IS RIYA', dtype='<U13')In [20]:np.char.lower(a)
## This turns every letter to lowercase.
Out[20]:array('hi it is riya', dtype='<U13')In [21]:np.char.split(a)
## It splits every word.
Out[21]:array(list(['hi', 'it', 'is', 'riya']), dtype=object)In [40]:np.char.strip(a,'h')
## It is used for removing beggining or last letter of word.
Out[40]:array('i it is riya', dtype='<U13')In [41]:np.char.strip(a,'a')Out[41]:array('hi it is riy', dtype='<U13')In [43]:np.char.splitlines("hello\nhow it is going\t well")
## It splits where there is next line.
Out[43]:array(list(['hello', 'how it is going\t well']), dtype=object)In [44]:np.char.replace(a,'i','k')
## Used to replace some char with another one.
Out[44]:array('hk kt ks rkya', dtype='<U13')

Mathematical Operations

Let's See addition, subtraction, multiplication, division, square root, and the dot product of arrays which can be smoothly done by numpy.

In [50]:x=np.array([[1,2],[3,4]])
y=np.array([[5,6],[7,8]])
print(x+y)
print(np.add(x,y))
print(x-y)
print(np.subtract(x,y))
OUTPUT[[ 6 8]
[10 12]]
[[ 6 8]
[10 12]]
[[-4 -4]
[-4 -4]]
[[-4 -4]
[-4 -4]]
In [51]:print(x*y)
print(np.multiply(x,y))
OUTPUT[[ 5 12]
[21 32]]
[[ 5 12]
[21 32]]
In [52]:print(x/y)
print(np.divide(x,y))
print(np.sqrt(x))
OUTPUT[[0.2 0.33333333]
[0.42857143 0.5 ]]
[[0.2 0.33333333]
[0.42857143 0.5 ]]
[[1. 1.41421356]
[1.73205081 2. ]]
## Dot product / Matrix MultiplicationIn [5]:print(x.dot(y))OUTPUT[[19 22]
[43 50]]
In [6]:print(np.dot(x,y))OUTPUT[[19 22]
[43 50]]

We can also calculate the sum along a particular axis. In the following example, you can see how the sum function is useful in calculating some along rows, columns, and all elements.

print(x) 
print(np.sum(x))
print(np.sum(x,axis=0))
print(np.sum(x,axis=1))
OUTPUT
[[1 2]
[3 4]]
10
[4 6]
[3 7]

We can stack arrays horizontally and vertically. By default, the value of axis in following code is 0 (we can also specify it). Axis = 0 stacks arrays in rows while Axis =1 in columns.

a=np.array([1,2,3,4])
b=b**2
np.stack((a,b))
OUTPUT
array([[ 1, 2, 3, 4],
[ 1, 4, 9, 16]])
np.stack((a,b),axis=1)OUTPUTarray([[ 1, 1],
[ 2, 4],
[ 3, 9],
[ 4, 16]])

We can reshape the array according to the shape required.

print(a.reshape((4,2)))[[ 1  2]
[ 3 4]
[ 1 4]
[ 9 16]]

These are the basics of NumPy yet there are many more. You can refer to the official documentation for more insights.

Thanks For Reading.

--

--