Exploring Python’s Numpy package

Numpy is a Python package which is well known for its data-crunching functions. It is one of the most used Python packages for Data Science. We will look into the package in brief below:-

To start with, import the numpy package

import numpy as np

Few striking points when you use numpy functions/objects:-
1. When you use traditional list, then you can include elements with different data types. But, numpy array can’t have elements of different data types

2. You can perform operation on each element of Numpy array, but you can’t do the same with a list. Example below:-

x = [1,2,3]
y = numpy.array([1,2,3])
x*3 will throw an error
y*3 
will give you output as 3,6,9

3. How to store a list in a numpy array?

x = [4,6,7]
z = numpy.array(x)

4. How to create a 2 Dimensional numpy array?

x = numpy.array([[1,2,3],[9,8,7]])

Output
[[1 2 3] [9 8 7]]

5. The first cell in a two-dimensional array will have the address [0,0]. Thus to access the 2nd row and 3 rd column of a 2D array, you should give the address as x[1][2]

6. You can directly convert a list of list into 2D array by passing the list in numpy.array() function

7. To access all the columns of 14th row, use the below command

x[13,:]

8. If you want to add two 2D array, then you can do it by ‘+’ operator. Example below:-

x = numpy.array([[1,2,3],[9,8,7]])
y = numpy.array([[4,5,6],[3,4,5]])
print(x+y)

Output

[[ 5 7 9] [12 12 12]]

9. Different built-in functions in Numpy package

a. sum()
b. sort()
c. mean()
d. median()
e. corrcoef()
f. std()

10. Generate sample data from

x = numpy.random.normal((3,0.5,100),2)

The above code will get you 100 sample with distribution mean of 3 and standard deviation of 0.5.

Numpy contains a very very diverse set of mathematical function. I could have copied it from somewhere !! But here is a website which seems to have all the built-in mathematical functions of numpy. Do check out.

 

Leave a Reply

Your email address will not be published. Required fields are marked *