illustration of Numpy in Python | applied electronics engineering

# illustration of Numpy in Python

By Applied Electronics - Monday, July 4, 2016 No Comments
Numpy is a array python package that is used to do calculation with array in python. With numpy it is easy to work with array. Here some illustration of using Numpy is shown. First we import the numpy module as np and then use np name instead of numpy.

We then show how to create 1D array, 2D array and how to get dimension and shape information. We show how to convert the 1D array to 2D. We show how to use the copy method to make a copy of an array and so forth.

import numpy as np

# defining an array in numpy:
a = np.array([1,2,3,4,5,6]) #this is same as writing numpy.array()
# print the output a arrayprint(a)
[1 2 3 4 5 6]

# print the dimension of arrayprint(a.ndim)
1

# print the shape of a arrayprint(a.shape)
(6,)
# transform the array in 2D matrix
b = a.reshape((2,3))  #reshape((rows,cols))
print(b)
[[1 2 3]
[4 5 6]]

# print the dimension of b
print(b.ndim)
2

# print the shape of b
print(b.shape)
(2, 3)

# create a copy
c = a.copy()
d = b.copy()
print(c)
[1 2 3 4 5 6]
print(d)
[[1 2 3]
[4 5 6]]

# replacing element of array
b[0][0] = 7
print(b)
[[7 2 3]
[4 5 6]]

# Operation in numpy are elementwise
print(a)
[7 2 3 4 5 6]
print(a*2)
[14  4  6  8 10 12]

print(b)
[[7 2 3]
[4 5 6]]
print(b**2)
[[49  4  9]
[16 25 36]]

# accessing elements of an array
print(a)
[7 2 3 4 5 6]
print(a[np.array([1,2])])
[2 3]
# get elements satisfying certain conditions
print(a)
[7 2 3 4 5 6]
print(a>4)
[ True False False False  True  True]
print(a[a>4])
[7 5 6]