Numpy Part -1

Numpy Part -1

Introduction

  1. NumPy is the fundamental package for scientific computing in Python.

  2. It is a Python library that provides a multidimensional array object, various derived objects (such as masked arrays and matrices), and an assortment of routines for fast operations on arrays, including mathematical, logical, shape manipulation, sorting, selecting, I/O, discrete Fourier transforms basic linear algebra, basic statistical operations, random simulation and much more.

  3. At the core of the NumPy package, is the ndarray object.

  4. This encapsulates n-dimensional arrays of homogeneous data types, with many operations being performed in compiled code for performance

Numpy vs Python Sequence

  1. NumPy arrays have a fixed size at creation, unlike Python lists (which can grow dynamically). Changing the size of an ndarray will create a new array and delete the original.

  2. The elements in a NumPy array are all required to be of the same data type, and thus will be the same size in memory. The exception: one can have arrays of (Python, including NumPy) objects, thereby allowing for arrays of different sized elements.

  3. NumPy arrays facilitate advanced mathematical and other types of operations on large numbers of data. Typically, such operations are executed more efficiently and with less code than is possible using Python’s built-in sequences.

  4. A growing plethora of scientific and mathematical Python-based packages are using NumPy arrays; though these typically support Python-sequence input, they convert such input to NumPy arrays prior to processing, and they often output NumPy arrays. In other words, in order to efficiently use much (perhaps even most) of today’s scientific/mathematical Python-based software, just knowing how to use Python’s built-in sequence types is insufficient - one also needs to know how to use NumPy arrays.

Creating an nd - array

  1. By passing a tuple

     array1=(1,2,3,4)
     np.array(array1)
    
  2. By passing a list

     array2=[1,2,3,4]
     np.array(array2)
    
  3. Arrays in programming are always 1dimensional

    • When we write a 2d array example :

        array[2][3]-----what it represents is 
        We have 2 1 dimensional array of size 3
      
        so while declaring it will be like 
        array[2][3]=[[1,2,3]---first one dimensional array
                      [4,5,6]] ----second one dimensional array      
      
        on similar lines if we have 3 dimensional array
        array[3][4][1]----this will imply we have 
        3 2- dimensional array of size 4
        But 2-dimensional array are 1d arrays 
        hence we have 4 1d array of size 1
        It will look like
         [[[1]],[[1]],[[1]],[[1]]]
      
  4. Using np. arange()

     np.arange(1,10)
    
    • arange(stop): Values are generated within the half-open interval [0, stop) (in other words, the interval including start but excluding stop).

    • arange(start, stop): Values are generated within the half-open interval [start, stop).

    • arange(start, stop, step) Values are generated within the half-open interval [start, stop), with spacing between values given by step.

  5. Re-shaping the nd array

     a = np.arange(6).reshape((3, 2))
     # 6 should be a product of 3,2
    
  6. np.ones & np. zeros

     np.ones((2, 1))  ## 2 - columns and 1 is rows
     # on similar lines we can replace ones with zeros
     ##array([[1.],
     ##       [1.]])
    
  7. np.linspace

    • Return evenly spaced numbers over a specified interval.

        np.linspace(2.0, 3.0, num=5)
        ## array([2.  , 2.25, 2.5 , 2.75, 3.  ])
      
  8. np.identity

      np.identity(3)
     ##array([[1.,  0.,  0.],
          ##  [0.,  1.,  0.],
          ##  [0.,  0.,  1.]])
    

Array Attributes

  1. Dimension : Technically dimension basically imples the number of points required to represent a given value in a given space

    example : 1. in 2d space we need two points hence 2-dimension

    2. in 3d space we nedd 3 points hence 3-dimension

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

     import numpy as np
     arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
     print(arr.shape)
    
  3. size

    • Equal to np.prod(a.shape), i.e., the product of the array’s dimensions.

    • Number of elements in the array.

  4. dtype

    • A data type object (an instance of numpy.dtype class) describes how the bytes in the fixed-size block of memory corresponding to an array item should be interpreted. It describes the following aspects of the data.

Iterating through an array using nd-iter

import numpy as geek 

# creating an array using arrange 
# method
a = geek.arange(12)

# shape array with 3 rows and 
# 4 columns 
a = a.reshape(3,4) 

print('Original array is:')
print(a)
print()  

# Transpose of original array
b = a.T 

print('Modified array is:')
for x in geek.nditer(b): 
    print(x)

##output :
## 0 1 2 3 4 5 6 7 8 9 10 11

Changing the data type

  1. astype() :Copy of the array, cast to a specified type

  2. By default, astype always returns a newly allocated array. If this is set to false, and the dtype, order, and subok requirements are satisfied, the input array is returned instead of a copy.

     x = np.array([1, 2, 2.5])
     print(x)
     print(x.astype(int))
     #array([1. ,  2. ,  2.5])
     #array([1, 2, 2])
     ## a new copy of the array is created as copy is true