Numpy Basics

Why Numpy over Lists?

  1. Speed of computation is faster
  2. Designed for data analysis
  3. Vector operations can be performed
  4. Concise and easy to read/write

Learn By Examples

Create a 3*3 array using predefined lists

Element Wise Multiplication

Create array of given dimension filled with given integer value

Create array filled with multiples of given number

Create a checkerboard matrix of size n*n

Explanation

  • np.tile can be used to repeat an array any number of times across any number of dimensions
  • Checkerboard's smallest unit is

  • Since smallest unit is already 2x2, whatever is this required board_size, we will divide it by 2

Reference

Extract all elements of 2nd column in 2D array

Extract border row, column of numpy array

Binomial Distribution

Problem Statement

Generate a binomial distribution, tested 10 times, given the number of trials(n) and probability(p) of each trial.

Input

The input will contain seed, n and p in the same order.

Output

The output should contain a numpy array with 10 numbers representing the required binomial distribution.

Conclusion

  1. Numpy arrays are significantly faster than lists when it comes to mathematical operations
  2. Numpy operations are concise, and easy to read & write.
  3. Numpy arrays are built for vector mathematics so that element wise calculations can be easily carried out.
  4. While in lists, one would have to write a for-loop or list comprehension for basic things like squaring all numbers in the list, the equivalent on a numpy array will simply be "array_name * 2".

References

Thank the author. Fork this blog.


Tagged in pythondata-analysisnumpy