Python

NumPy

The NumPy library is the core library for scientific computing in Python.

Importing NumPy

import numpy as np

Data Types

  • np.int64: Signed 64-bit integer types
  • np.float32: Standard double-precision floating point
  • np.complex: Complex numbers represented by 128 floats
  • np.bool: Boolean type storing TRUE and FALSE values
  • np.object: Python object type
  • np.string_: Fixed-length string type
  • np.unicode_: Fixed-length unicode type

Creating Arrays

Array Creation

# 1D array
a = np.array([1, 2, 3])
 
# 2D array
b = np.array([(1.5, 2, 3), (4, 5, 6)], dtype=float)
 
# 3D array
c = np.array([[(1.5, 2, 3), (4, 5, 6)], 
              [(3, 2, 1), (4, 5, 6)]], dtype=float)

Initial Placeholders

# Create an array of zeros
np.zeros((3, 4))
 
# Create an array of ones
np.ones((2, 3, 4), dtype=np.int16)
 
# 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))

Array Mathematics

Arithmetic Operations

# Addition
b + a
np.add(b, a)
 
# Subtraction
g = a - b
np.subtract(a, b)
 
# Multiplication
a * b
np.multiply(a, b)
 
# Division
a / b
np.divide(a, b)
 
# Dot product
e.dot(f)
 
# Other operations
np.exp(b)     # Exponentiation
np.sqrt(b)    # Square root
np.sin(a)     # Print sines of an array
np.cos(b)     # Elementwise cosine
np.log(a)     # Elementwise natural logarithm

Comparison

# Elementwise comparison
a == b
>>> array([[False, True, True],
       [False, False, False]], dtype=bool)
 
a < 2
>>> array([True, False, False], dtype=bool)
 
 
# Arraywise comparison
np.array_equal(a, b)

Aggregate Functions

a.sum()                # Array-wise sum
a.min()                # Array-wise minimum value
b.max(axis=0)          # Maximum value of an array row
b.cumsum(axis=1)       # Cumulative sum of the elements
a.mean()               # Mean
np.median(b)           # Median
np.corrcoef(a)         # Correlation coefficient
np.std(b)              # Standard deviation

Array Manipulation

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()

Sorting Arrays

# Sort an array
a.sort()
 
# Sort the elements of an array's axis
c.sort(axis=0)

Array Shape Manipulation

# Transpose array
i = np.transpose(b)
i.T
 
# Flatten the array
b.ravel()
 
# Reshape array
g.reshape(3, 2)
 
# Resize array
h.resize((2, 6))

Adding/Removing Elements

np.append(h, g)        # Append items to an array
np.insert(a, 1, 5)     # Insert items in an array
np.delete(a, [1])      # Delete items from an array

Combining Arrays

# Concatenate arrays
np.concatenate((a, d), axis=0)
 
# Stack arrays vertically (row-wise)
np.vstack((a, b))
np.r_[e, f]
 
# Stack arrays horizontally (column-wise)
np.hstack((e, f))
np.column_stack((a, d))
np.c_[a, d]

Splitting Arrays

# Split the array horizontally
np.hsplit(a, 3)
 
# Split the array vertically
np.vsplit(c, 2)

I/O Operations

Saving & Loading On Disk

# Save array to disk
np.save('my_array', a)
 
# Save multiple arrays to disk
np.savez('array.npz', a, b)
 
# Load array from disk
np.load('my_array.npy')

Saving & Loading Text Files

# Load data from text file
np.loadtxt('myfile.txt')
np.genfromtxt('my_file.csv', delimiter=',')
 
# Save array to text file
np.savetxt('myarray.txt', a, delimiter=' ')

Inspecting Your Array

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

Getting Help

np.info(np.ndarray.dtype)

Last updated on