NumPy
The NumPy library is the core library for scientific computing in Python. This Python NumPy cheat sheet is a quick reference for NumPy beginners looking to get started with data analysis.
import convention
import numpy as np
How to create arrays
a = np.array([1,2,3])
b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
c = np.array([[(1.5,2,3), (4,5,6)], [(3,2,1), (4,5,6)]], dtype = float)
Create an array of zeros : np.zeros((3,4))
Create an array of ones : np.ones((2,3,4),dtype=np.
Create an array of evenly spaced values (step value) : d = np.arange(10,25,5)
Create an array of evenly spaced values (number of samples) : np.linspace(0,2,9)
Create a constant array : e = np.full((2,2),7)
Create a 2X2 identity matrix : f = np.eye(2)
Create an array with random values : np.random.random((2,2))
Create an empty array : np.empty((3,2))
Saving and Loading On Disk
np.save(‘my_array’, a)
np.savez(‘array.npz’, a, b)
np.load(‘my_array.npy’)
Saving & Loading Text Files
np.loadtxt(“myfile.txt”)
np.genfromtxt(“my_file.csv”, delimiter=’,’)
np.savetxt(“myarray.txt”, a, delimiter=” “)
Data Types
Signed 64-bit integer types: np.int64
Standard double-precision floating point : np.float32
Complex numbers represented by 128 floats : np.complex
Boolean type storing TRUE and FALSE values : np.bool
Python object type : np.object
Fixed-length string type : np.string_
Fixed-length unicode type : np.unicode_
Inspecting Your Array
Array dimensions : a.shape
Length of array : len(a)
Number of array dimensions : b.ndim
Number of array elements : e.size
Data type of array elements : b.dtype
Name of data type : b.dtype.name
Convert an array to a different type : b.astype(int)
Help
np.info(np.ndarray.dtype)
Subtraction : g = a – b
array([[-0.5, 0. , 0. ], [-3. , -3. , -3. ]])
np.subtract(a,b)
Addition : b + a
array([[ 2.5, 4. , 6. ], [ 5. , 7. , 9. ]])
np.add(b,a)
Division : a / b
array([[ 0.66666667, 1. , 1. ], [ 0.25 , 0.4 , 0.5 ]])
np.divide(a,b)
Multiplication : a * b
- Multiplication : np.multiply(a,b)
- Exponentiation : np.exp(b)
- Square root : np.sqrt(b)
- Print sines of an array : np.sin(a)
- Element-wise cosine : np.cos(b)
- Element-wise natural logarithm : np.log(a)
- Dot product : e.dot(f)
Element-wise comparison : a == b
array([[False, True, True], [False, False, False]], dtype=bool)
Element-wise comparison : a < 2
array([True, False, False], dtype=bool)
Array-wise comparison : np.array_equal(a, b)
Aggregate Functions
Array-wise sum : a.sum()
Array-wise minimum value : a.min()
Maximum value of an array row : b.max(axis=0)
Cumulative sum of the elements : b.cumsum(axis=1)
Mean : a.mean()
Median : b.median()
Correlation coefficient : a.corrcoef()
Standard deviation : np.std(b)
Copying Arrays
Create a view of the array with the same data : h = a.view()
Create a copy of the array : np.copy(a)
Create a deep copy of the array : h = a.copy()
Sort an array : a.sort()
Sort the elements of an array’s axis : c.sort(axis=0)
Transposing Array
i = np.transpose(b)
i.T
Changing Array Shape
Flatten the array
b.ravel()
g.reshape(3,-2)
Adding/Removing Elements
Return a new array with shape (2,6) : h.resize((2,6))
Append items to an array : np.append(h,g)
Insert items in an array : np.insert(a, 1, 5)
Delete items from an array : np.delete(a,[1])
Combining Arrays
Concatenate arrays :
np.concatenate((a,d),axis=0)
array([ 1, 2, 3, 10, 15, 20])
Stack arrays vertically (row-wise)
np.vstack((a,b))
array([[ 1. , 2. , 3. ],[ 1.5, 2. , 3. ],[ 4. , 5. , 6. ]])
Stack arrays vertically (row-wise) : np.r_[e,f]
np.hstack((e,f)) Stack arrays horizontally (column-wise) : array([[ 7., 7., 1., 0.], [ 7., 7., 0., 1.]])
Create stacked column-wise arrays :
np.column_stack((a,d)) Create stacked column-wise arrays
array([[ 1, 10],[ 2, 15],[ 3, 20]])
Create stacked column-wise arrays : np.c_[a,d]
Split the array horizontally at the 3rd index
np.hsplit(a,3)
[array([1]),array([2]),array([
Split the array vertically at the 2nd index
np.vsplit(c,2)
[array([[[ 1.5, 2. , 1. ], [ 4. , 5. , 6. ]]]), array([[[ 3., 2., 3.], [ 4., 5., 6.]]])]