NumPy Basics Cheat Sheet Copying Arrays
>>> h = a.view()
>>> np.copy(a)
Create a view of the array with the same data
Create a copy of the array
Sorting Arrays
>>> a.sort() Sort an array
BecomingHuman.AI
>>> c.sort(axis=0) Sort the elements
>>> h = a.copy() Create a deep copy of the array of an array's axis
Data Types Subsetting, Slicing, Indexing
>>> np.int64 Signed 64-bit integer types
The NumPy library is the core library for
scientific computing in Python. It provides a
>>> np.float32 Standard double-precision floating point Subsetting
>>> np.complex Complex numbers represented by 128 floats
high-performance multidimensional array >>> a[2] 1 2 3 Select the element at the 2nd index
>>> np.bool Boolean type storing TRUE and FALSE 3
object, and tools for working with these arrays.
>>> np.object Python object type values >>> b[1,2] 1.5 2 3 Select the element at row 1 column 2
6.0 4 5 6 (equivalent to b[1][2])
>>> np.string_ Fixed-length string type
1D array 2D array 3D array >>> np.unicode_ Fixed-length unicode type
axis 1 axis 2 Slicing
1 2 3 axis 1 >>> a[0:2] Select items at index 0 and 1
1.5 2 3 1 2 3
array([1, 2])
axis 0 axis 0
4 5 6
Asking For Help >>> b[0:2,1]
array([ 2., 5.])
1.5 2
4 5
3
6
Select items at rows 0 and 1 in column 1
Creating Arrays >>> np.info(np.ndarray.dtype) >>> b[:1]
array([[1.5, 2., 3.]])
1.5 2
4 5
3
6
Select all items at row 0
(equivalent to b[0:1, :])
>>> c[1,...] Same as [1,:,:]
>>> a = np.array([1,2,3]) array([[[ 3., 2., 1.],
>>> b = np.array([(1.5,2,3), (4,5,6)], dtype = float) [ 4., 5., 6.]]])
>>> c = np.array([[(1.5,2,3), (4,5,6)], [(3,2,1), (4,5,6)]],dtype = float) Array Mathematics >>> a[ : :-1]
array([3, 2, 1])
Reversed array a
Initial Placeholders Arithmetic Operations
>>> np.zeros((3,4)) Create an array of zeros >>> g = a - b Subtraction Boolean Indexing
array([[-0.5, 0. , 0. ], >>> a[a<2] Select elements from a less than 2
>>> np.ones((2,3,4),dtype=np.int16) Create an array of ones [-3. , -3. , -3. ]]) 1 2 3
array([1])
>>> d = np.arange(10,25,5) Create an array of evenly spaced >>> np.subtract(a,b) Subtraction
values (step value)
>>> b + a Addition
>>> np.linspace(0,2,9) Create an array of evenly array([[ 2.5, 4. , 6. ],
spaced values (number of samples) [ 5. , 7. , 9. ]]) Fancy Indexing
>>> e = np.full((2,2),7) Create a constant array >>> np.add(b,a) Addition
>>> b[[1, 0, 1, 0],[0, 1, 2, 0]] Select elements (1,0),(0,1),(1,2) and (0,0)
>>> f = np.eye(2) Create a 2X2 identity matrix >>> a / b Division array([ 4. , 2. , 6. , 1.5])
>>> np.random.random((2,2)) Create an array with random values array([[ 0.66666667, 1. , 1. ],
[ 0.25 , 0.4 , 0.5 ]]) >>> b[[1, 0, 1, 0]][:,[0,1,2,0]] Select a subset of the matrix’s rows
>>> np.empty((3,2)) Create an empty array array([[ 4. ,5. , 6. , 4. ], and columns
>>> np.divide(a,b) Division [ 1.5, 2. , 3. , 1.5],
[ 4. , 5. , 6. , 4. ],
>>> a * b Multiplication [ 1.5, 2. , 3. , 1.5]])
array([[ 1.5, 4. , 9. ],
[ 4. , 10. , 18. ]])
I/O >>> np.multiply(a,b)
>>> np.exp(b)
Multiplication
Exponentiation
>>> np.sqrt(b) Square root
Saving & Loading On Disk >>> np.sin(a) Print sines of an array Array Manipulation
>>> np.save('my_array', a) >>> np.cos(b) Element-wise cosine
>>> np.savez('array.npz', a, b) >>> np.log(a) Element-wise natural logarithm Transposing Array Changing Array Shape
>>> e.dot(f) Dot product >>> i = np.transpose(b) Permute array dimensions
>>> np.load('my_array.npy')
array([[ 7., 7.], >>> b.ravel() Flatten the array
[ 7., 7.]]) >>> i.T Permute array dimensions >>> g.reshape(3,-2) Reshape, but don’t change data
Saving & Loading Text Files
>>> np.loadtxt("myfile.txt") Comparison
>>> np.genfromtxt("my_file.csv", delimiter=',')
>>> np.savetxt("myarray.txt", a, delimiter=" ")
>>> a == b
array([[False, True, True],
Element-wise comparison Adding/Removing Elements Combining Arrays
[False, False, False]], dtype=bool) >>> h.resize((2,6)) Return a new array with shape (2,6) >>> np.concatenate((a,d),axis=0) Concatenate arrays
>>> a < 2 Element-wise comparison array([ 1, 2, 3, 10, 15, 20])
>>> np.append(h,g) Append items to an array
array([True, False, False], dtype=bool) >>> np.vstack((a,b)) Stack arrays vertically (row-wise)
>>> np.insert(a, 1, 5) Insert items in an array array([[ 1. , 2. , 3. ],
Inspecting Your Array >>> np.array_equal(a, b) Array-wise comparison
>>> np.delete(a,[1]) Delete items from an array [ 1.5, 2. , 3. ],
[ 4. , 5. , 6. ]])
>>> a.shape Array dimensions
Aggregate Functions >>> np.r_[e,f] Stack arrays vertically (row-wise)
>>> len(a) Length of array >>> a.sum() Array-wise sum
Splitting Arrays >>> np.hstack((e,f))
array([[ 7., 7., 1., 0.],
Stack arrays horizontally
(column-wise)
>>> np.hsplit(a,3) Split the array [ 7., 7., 0., 1.]])
>>> b.ndim Number of array dimensions >>> a.min() Array-wise minimum value
[array([1]),array([2]),array([3])] index horizontally >>> np.column_stack((a,d)) Create stacked
>>> e.size Number of array elements >>> b.max(axis=0) Maximum value of an array row at the 3rd array([[ 1, 10], column-wise arrays
>>> b.dtype Data type of array elements >>> b.cumsum(axis=1) Cumulative sum of the elements [ 2, 15],
>>> np.vsplit(c,2) Split the array vertically at the 2nd index [ 3, 20]])
>>> b.dtype.name Name of data type >>> a.mean() Mean [array([[[ 1.5, 2. , 1. ],
[ 4. , 5. , 6. ]]]), >>> np.c_[a,d] Create stacked
>>> b.astype(int) Convert an array to a different type >>> b.median() Median column-wise arrays
ht ps:/ w w.dat camp.com/com unity/blog/python- umpy-cheat-she t