Python Tutorial: Numpy-Array

Saturday, 3 July 2021

Numpy-Array



NumPy stands for Numerical Python.It is the core library for  scientific computing in Python. It consist of multidimensional  array objects, and tools for working with these arrays.

Arrays :

Numpy Array is a grid of values with same type, and is indexed  by a tuple of nonnegative integers. The number of dimensions of  it ,is the rank of the array; the shape of an array depends upon a  tuple of integers giving the size of the array along each  dimension.

Note:- Before numpy based programming ,it must be installed. It can be  installed using >pip install pandas command at command prompt

 1 D ARRAY

Any arrays can be single or multidimensional. The number of  subscript/index determines dimensions of the array. An array of one  dimension is known as a one-dimensional array or 1-D array

 

In above diagram num is an array ,it’s first element is at 0 index  position ,next element is at 1 and so on till last element at n-1 index  position. At 0 index position value is 2 and at 1 index position value  is 5

Example

import numpy as np
a = np.array([500, 200, 300])               # Create a 1D Array
print(type(a))                                       # Prints "<class 'numpy.ndarray'>"
print(a.shape)                                      # Prints "(3,)" means dimension of array 
print(a[0], a[1], a[2])                           # Prints "500 200 300"
a[0] = 150                                          # Change an element of the array 
print(a)                                                                 


 

1 D ARRAY

Creation of 1D array Using functions  import numpy as np

p = np.empty(5)         # Create an array of 5 elements with random values  print(p)

a1 = np.zeros(5)                        # Create an array of all zeros float values 

print(a1)                                          # Prints "[0. 0. 0. 0. 0.]"

a2 = np.zeros(5, dtype = np.int)    # Create an array of all zeros int values 

print(a2)                                          # Prints "[0. 0. 0. 0. 0.]"

b = np.ones(5)                                  # Create an array of all ones 

print(b)                                             # Prints "[1. 1. 1. 1. 1.]"

c = np.full(5, 7)                                # Create a constant array

print(c)                                            # Prints "[7 7 7 7 7]"

e = np.random.random(5)       # Create an array filled with random values  

print(e)

1 D ARRAY

Difference between Numpy array and list

Lists

Array

List can have elements of different data types for example, [1,3.4, ‘hello’, ‘a@’]

All elements of an array are of same data type for example, an array of floats may be: [1.2, 5.4, 2.7]

Elements of a list are not stored contiguously in memory.

Array elements are stored in contiguous memory locations. This makes operations on arrays faster than lists.

Lists do not support element wise operations, for example, addition, multiplication, etc. because elements may not be of same type.

Arrays support element wise operations. For example, if A1 is an array, it is possible to say A1/3 to divide each element of the array by 3.

Lists can contain objects of different datatype that Python must store the type information for every element along with its element value. Thus lists take more space in memory and are less efficient.

NumPy array takes up less space in memory as compared to a list because arrays do not require to store datatype of each element separately.

List is a part of core Python.

Array (ndarray) is a part of NumPy library.

1 D ARRAY

Create 1D from string  

import numpy as np
data =np.fromstring('1 2', dtype=int, sep=' ')
print(data)

Note:- in fromstring dtype and sep argument can be changed.

Create 1D from buffer

numpy array from range  numpy.arange(start, stop, step, dtype)  

#Program 1

import numpy as np
x = np.arange(5) #for float value specify dtype = float as argument 
print(x)       #print [0    1  2   3       4]

 

#Program 2

import numpy as np
x = np.arange(10,20,2)
print (x) #print [10       12     14     16     18]

1 D ARRAY

Create 1D from array

        Copy function is used to create the copy of the existing array. 

#Program

import numpy as np 

x = np.array([1, 2, 3]) 

y = x

z = np.copy(x) 

x[0] = 10

print(x) 

print(y) 

print(z)

Note that:, when we modify x, y changes, but not z:

 1 D ARRAY SLICES

        Slicing   of  numpy  array elements is just similar  to slicing of list elements. 

# Program

import numpy as np
data = np.array([5,2,7,3,9])
print (data[:])#print [5 2 7 3 9]
print(data[1:3]) #print [2 7]
print(data[:2]) #print [5 2]
print(data[-2:]) #print [3 9]

1 D ARRAY JOINING

Joining of two or more one dimensional array  is possible with the help of concatenate() function of numpy object.

#Program

import numpy as np 
a = np.array([1, 2, 3])
b = np.array([5, 6]) 
c=np.concatenate([a,b,a]) 
print(c)                                                 #print [1 2 3 5 6 1 2 3]

 

Print all subsets of a 1D Array
       If A {1, 3, 5}, then all the possible/proper subsets of A are { }, {1}, {3}, {5}, {1,3}, {3, 5}


#Program

import pandas as pd 
import numpy as np 
def sub_lists(list1):
    # store all the sublists
    sublist = [[]] 
    # first loop
    for i in range(len(list1) + 1): 
    # second loop
        for j in range(i + 1, len(list1) + 1):
        # slice the subarray 
            sub = list1[i:j] 
            sublist.append(sub)
    return sublist
x = np.array([1, 2, 3,4])  # driver code 
print(sub_lists(x))
 
OUTPUT
[[], array([1]), array([1, 2]), array([1, 2, 3]), array([1, 2, 3, 4]), array([2]), array([2, 3]), array([2, 3, 4]), array([3]), array([3, 4]), array([4])]

 

Basic arithmetic operation on  1D Array

Aggregate operation on 1D  Array

#Program

import numpy as np

x = np.array([1, 2, 3,4])

y = np.array([1, 2, 3,4])

z=x+y

print(z) #print [2 4 6 8]  

z=x-y

print(z) #print [0 0 0 0]  

z=x*y

print(z) #print [ 1 4 9 16]

z=x/y

print(z) #print [1. 1. 1. 1.]  

z=x+1

print(z) #print [2 3 4 5] 

#Program

import numpy as np

x = np.array([1, 2, 3,4])

print(x.sum()) #print 10

print(x.min()) #print 1

print(x.max()) #print 4

print(x.mean())#print 2.5

print(np.median(x))#print 2.5

 


2 D ARRAY

An array of two dimensions/indexes /subscripts is known as a two- dimensional array or 2-D array.

In above diagram num is an array of two dimensions with 3 rows and 4 columns. Subscript of rows is 0 to 2 and columns is 0 to 3.

2 D ARRAY

Creation of 2D array

Two-dimension array can be created using array method with list object with two-dimensional elements.

#Program

import numpy as np

a = np.array([[3, 2, 1],[1, 2, 3]])

print(type(a)) 

print(a.shape) 

print(a[0][1]) 

a[0][1] = 150

print(a)

 

# Create a 2D Array

# Prints "<class 'numpy.ndarray'>" 

# Prints (2, 3)

# Prints 2

# Change an element of the array

# prints [[ 3 150     1] [  1     2    3]]

  2 D ARRAY

Creation of 2D array Using functions 

import numpy as np
p = np.empty([2,2])     # Create an array of 4 elements with random values 
print(p) 
a1 = np.zeros([2,2])                    # Create 2d array of all zeros float values 
print(a1)                                                              # Prints [[0. 0.][0. 0.]]
a2 = np.zeros([2,2], dtype = np.int) #Create an array of all zeros int values 
print(a2)                                                # Prints [[0 0] [0 0]]
b = np.ones([2,2])                                  # Create an array of all ones 
print(b)                                                  # Prints [[1. 1.] [1. 1.]]
c = np.full([2,2], 7)                                 # Create a constant array
print(c)                                                  # Prints [[7 7] [7 7]]
e = np.random.random([2,2])    # Create 2d array filled with random values 
print(e)

2D ARRAY

Creation of 2D array from 1D array

We can create 2D array from 1d array using reshape() function.

#Program

import numpy as np

A = np.array([1,2,3,4,5,6])

B = np.reshape(A, (2, 3))  print(B)

OUTPUT 

[[1 2 3]

[4 5 6]]

2 D ARRAY SLICES

Slicing    of numpy 2d array elements is just similar to slicing of list elements with 2 dimension. 

#Program

import numpy as np

A = np.array([[7, 5, 9, 4],

[ 7, 6, 8, 8],

[ 1, 6, 7, 7]])

print(A[:2, :3]) #print elements of 0,1 rows and 0,1,2 columns

print(A[:3, ::2])  #print elements of 0,1,2 rows and alternate column position

print(A[::-1, ::-1]) #print elements in reverse order 

print(A[:, 0]) #print all elements of 0 column 

print(A[0, :])  #print all elements of 0 rows 

print(A[0]) #print all elements of 0 row


Output:

print(A[:2, :3]) #print elements of 0,1 rows and 0,1,2 columns

7

5

9

4

7

6

8

8

1

6

7

7

print(A[:3, ::2])  #print elements of 0,1,2 rows and alternate column position

7

5

9

4

7

6

8

8

1

6

7

7


 print(A[::-1, ::-1]) #print elements in reverse order

            print(A[:, 0]) #print all elements of 0 column 

7

5

9

4

7

6

8

8

1

6

7

7

print(A[0, :])  #print all elements of 0 rows 

7

5

9

4

7

6

8

8

1

6

7

7

print(A[0]) #print all elements of 0 row

7

5

9

4

7

6

8

8

1

6

7

7

No comments:

Post a Comment