Skip to content

Types of NumPy Arrays

Mardav Jadaun edited this page Feb 6, 2024 · 3 revisions

One-dimensional Arrays

  • These are similar to Python lists but with more functionality and optimized for numerical operations.
  • Represented as a single row or column of elements.
  • Created using the numpy.array() function.
  import numpy as np

  arr1d = np.array([1, 2, 3, 4, 5])

Two-dimensional Arrays

  • These are like tables, with rows and columns.
  • You can think of them as arrays of arrays, where each inner array represents a row.
  • Created using nested lists or by reshaping a one-dimensional array.
  import numpy as np

  arr2d = np.array([[1, 2, 3], [4, 5, 6]])

Multi-dimensional Arrays

  • These are arrays with more than two dimensions, like a cube or higher-dimensional space.
  • Useful for representing volumetric data or tensors in machine learning.
  • Created by reshaping arrays or using functions like 'numpy.zeros()' or 'numpy.ones()'
  import numpy as np

  arr3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

Structured Arrays

  • These are arrays where each element can have different data types.
  • Useful for handling structured data, like tables with different types of columns.
  • Created using a structured data type descriptor.
  import numpy as np 
  
  dtype = [('name', 'S10'), ('age', int)]
  data = [('Alice', 25), ('Bob', 30)]
  arr_structured = np.array(data, dtype=dtype)

Masked Arrays

  • These are arrays that have a mask associated with them, indicating invalid or missing values.
  • Useful for handling datasets with missing or invalid data.
  • Created using the 'numpy.ma.masked_array()' function.
  import numpy as np 
 
  arr = np.ma.array([1, 2, 3, -99, 5], mask=[0, 0, 0, 1, 0])

Matrix Arrays

  • These are special types of 2D arrays used for linear algebra operations.
  • Provides convenience functions for matrix operations like matrix multiplication.
  • Created using the 'numpy.matrix()' function.
  import numpy as np 

  mat = np.matrix([[1, 2], [3, 4]])

These are the main types of arrays in NumPy, each designed for specific use cases. Understanding these types will help you effectively utilize NumPy for various numerical computing tasks.

Made with ♥️ by Mardav Jadaun

Clone this wiki locally