Sunday, December 3, 2023
HomeAlgorithmsIntroduction to NumPy: useful cheat sheets

# Introduction to NumPy: useful cheat sheets The NumPy library is the core library for scientific computing in Python. It provides a high-performance multidimensional array object, and tools for working with these arrays. This post is an effort to collect useful numpy commands in one place to make your computing task easier. Before moving forward, make sure that you’ve installed Python and NumPy library in your system.

To install Python in Windows follow previous article here

### First of all, after installing Numpy library, use the following import convention:

>>> import numpy as np

### To create NumPy 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)

here,  a is 1D – array, b is 2D array and c is 3D array

### Use of initial place holders:

>>> np.zeros((3,4)) Create an array of zeros
>>> np.ones((2,3,4),dtype=np.int16) Create an array of ones
>>> d = np.arange(10,25,5) Create an array of evenly spaced values (step value)
>>> np.linspace(0,2,9) Create an array of evenly spaced values (number of samples)
>>> e = np.full((2,2),7) Create a constant array
>>> f = np.eye(2) Create a 2X2 identity matrix
>>> np.random.random((2,2)) Create an array with random values
>>> np.empty((3,2)) Create an empty array

### Basic I/O

>>> np.save(‘my_array’, a)
>>> np.savez(‘array.npz’, a, b)

>>> np.genfromtxt(“my_file.csv”, delimiter=’,’)
>>> np.savetxt(“myarray.txt”, a, delimiter=” “)

>>> a.shape Array dimensions
>>> len(a) Length of array
>>> b.ndim Number of array dimensions
>>> e.size Number of array elements
>>> b.dtype Data type of array elements
>>> b.dtype.name Name of data type
>>> b.astype(int) Convert an array to a different type

datasagarhttp://www.DataSagar.com
The author of this blog post is a technology fellow, an IT entrepreneur, and Educator in Kathmandu Nepal. With his keen interest in Data Science and Business Intelligence, he writes on random topics occasionally in the DataSagar blog.
RELATED ARTICLES