In [1]:
import numpy as np
In [2]:
#creating array by providing numerical values
arr = np.array([[1,2,3,4],[5,6,7,8]])
arr
Out[2]:
array([[1, 2, 3, 4],
       [5, 6, 7, 8]])
In [3]:
#numpy supports multidimensional array
arr = np.arange(12)
arr
Out[3]:
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
In [4]:
#we can format the array to different dimensions
#Let's convert the arrray into 3 x 4
arr.reshape(3,4)
arr
Out[4]:
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
In [5]:
#The array is not reshaped as it returns a different objet
#To get what we intend let's assign the returned the object to arr itself
arr=arr.reshape(3,4)
arr
Out[5]:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
In [6]:
#iterating over the array
for x in np.nditer(arr):
    print(x)
0
1
2
3
4
5
6
7
8
9
10
11
In [7]:
#multiplication
arr*arr
Out[7]:
array([[  0,   1,   4,   9],
       [ 16,  25,  36,  49],
       [ 64,  81, 100, 121]])
In [8]:
#addition
arr+arr
Out[8]:
array([[ 0,  2,  4,  6],
       [ 8, 10, 12, 14],
       [16, 18, 20, 22]])
In [9]:
#sum of all elements
arr.sum()
Out[9]:
66
In [10]:
#sum of each row separately
arr.sum(axis=0)
Out[10]:
array([12, 15, 18, 21])
In [11]:
#sum of each column separately
arr.sum(axis=1)
Out[11]:
array([ 6, 22, 38])
In [12]:
#slicing
arr[0:2]
Out[12]:
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])
In [13]:
#last row
arr[-1]
Out[13]:
array([ 8,  9, 10, 11])