Numpy Introduction Lecture

Jul 18, 2024

Numpy Introduction Lecture

Introduction to Numpy

  • Numpy is a powerful library in Python used for numerical computations.
  • Comparable to lists in Python but significantly faster.
  • List can perform similar tasks but are slower.
  • Numpy arrays are up to 50 times faster than Python lists.
  • Preferred for processing due to speed and efficiency.

Key Features of Numpy

  • Contiguous Memory Allocation:

    • Unlike lists, Numpy arrays are stored in continuous memory locations.
    • This continuous storage leads to quicker access and manipulation.
    • Example: In a list, elements are stored at varied memory addresses requiring additional access steps.
    • In Numpy, knowing the memory address of the first element allows direct access to subsequent elements.
  • Implemented in Multiple Languages:

    • Primarily written in Python but core parts requiring fast computation are written in C and C++.
    • This multi-language approach aids in achieving high performance.

Coding with Numpy

Basic Code Structure

  • To use Numpy, it needs to be imported in the code:
    import numpy as np
    
    This command lets the computer know that Numpy library functions will be used.
  • Example of creating an array:
    arr = np.array([1, 2, 3, 4, 5])
    print(arr)
    
    • np.array() creates an array with the given elements.
    • Printing arr will display the array elements.

Aliases and Shortcuts

  • Large names like numpy can be alias to shorten and simplify the code.
  • By using import numpy as np,
    • np becomes a shorthand to reference the Numpy library.
    • Example: np.array() instead of numpy.array().

Checking Version

  • To check the version of the Numpy library used:
    print(np.__version__)
    
    • This gives the installed version of Numpy.

Conclusion

  • Numpy is a critical tool in Python for efficient numerical computations due to its speed and continuous memory storage and its multi-language implementation.
  • Understanding and utilizing Numpy's functions is essential for efficient coding in data processing and scientific computation tasks.