Wednesday, 27 May 2020

Python Numpy | Numpy in Python

Python Numpy | Numpy in Python | Arrays in Python


How to create Numpy arrays  using array() method, fromiter() method, arange() method.


NumPy Arrays

  • It is also known as N-Dimensional Array(ndarray).
  • It can be of two types
            One-Dimensional Array(are also known as vectors)
            Multi-Dimensional Array(are also known as matrices)

  • It is Linear Algebra Library in Python. ‘import numpy’.
  • It describes the element in array of the same datatype.
  • It is used for performing mathematical and logical operations    on arrays.


numpy array

how to define array in numpy





How to create arrays?




python functions



python functions in numpy

There are many ways to create numpy arrays . Lets discuss 


array() method

The array() is useful for creating ndarrays from existing lists and tuples.

Syntax:

variable_name=numpy.array(<arrayConvertibleObject>,dtype)

numpy has been imported as np
dtype is optional


1. Creating numpy array using array() method with list.

             first we import a library for creating arrays.

Creating One Dimensional array using array method with the help of list:

import numpy as np      
list1=[2,3,4]                      
array1=np.array(list1)
print(array1)

Creating Two Dimensional array using array method with the help of 2 lists:

import numpy as np
list1=[2,3,4]
list2=[4,3,2]
array2=np.array([list1,list2])  
# whenever you use multiple list to create array we write as 
# variable_name=numpy_alias_name.array([,])
print(array2)


two dimensional array using two list


Here, We have write  'import numpy as np ' numpy is a python library which is used to create array. np means alias name of numpy. It is creating for using numpy method so we create an alias name through which we can invoke numpy methods with a dot operator. 
We can create array using list, tuples and directly with the help of array method. Dictionary and Strings are not good for creating array with array method. 

If you try to create array using dictionary and strings, you can do successfully. 
But you cannot access individual elements of the array using indexes.It generates error.

See example:

dictionary array




2.  Creating numpy array using array() method with tuple.


Creating One Dimensional array using array method with the help of tuple:

import numpy as np      
tup1=(4,5,6)
array1=np.array(tup1)
print(array1)

Creating Two Dimensional array using array method with the help of 2 tuples:

import numpy as np
tup1=(4,5,6)
tup2=(6,5,4)
array2=np.array([tup1,tup2])  
print(array2)


creating array using tuple





3.  Creating numpy array using array() method directly.


Creating One Dimensional array using array method :

import numpy as np      

array1=np.array([2,5,7])
print(array1)

Creating Two Dimensional array using array method : 

import numpy as np

array2=np.array([[2,4,6],[6,7,8]])  
print(array2)

python numpy array method


The reason for this is that array() created object array or special unicode type arrays and accessing these arrays with indexes generates error.

The solution of the above problem is fromiter() method.






fromiter() method

We can create array or ndarray from all sequences such as list,tuple,strings,dictionaries etc. using fromiter() method.It supports all numeric and non-numeric sequences.

The fromiter() function is useful , when you want to create an ndarray from a non-numeric sequence.

 However, fromiter() is good for creating array using dictionaries and strings.

When we create ndarray from a dictionary using fromiter().
It takes only keys of the dictionary.Please remember that with fromiter() , the dtype argument must be given.

Syntax:

numpy.fromiter(<iterable sequence>,dtype=<datatype>,[count=<number of elements to be read>])





import numpy as np

# creating ndarray from dictionary with string keys

dic={'name':'amit','salary':100000,'age':45}
array1=np.fromiter(dic,'U1')
print(array1)

# creating ndarray from dictionary with integer

dic1={1:2,3:4,4:6,7:0}
array2=np.fromiter(dic1,dtype=np.int32)
print(array2)

# creating ndarray from string

str="ILovePython"
array3=np.fromiter(str,'U1')
print(array3)


numpy fromiter method


Here, We create an ndarray from dictionary with string type keys. As we know fromiter function only takes keys as array elements.

We also create an ndarray from dictionary with integer type keys. And created ndarray from individual letters of a string using fromiter() function.


We can also create from list and tuples.The method would be same i.e. the iterable name and dtype as the required arguments.

The function fromiter() also supports one more argument called count using which we can put a limit on how many elements from the iterable are to be picked for the ndarray.

For example :

we have a string of 20 letters including blank spaces and you want to create a ndarray of first 10 letters so you can give additional argument count=10. It will take only 10 letters as elements.


syntax of fromiter method

 You can use count argument with dictionary also.


arange() method

The arange() method is similar to Python's range() function. Python's range() method returns a list but arange() method returns ndarray.The arange() function creates a numpy array with evenly spaced values within a specified numerical range.

Syntax:

<arrayname>=numpy.arange([start],[stop],[step],[dtype])

  • Here, The start, stop and step attribute provide the values for starting value, stopping value and step value for a numerical range. Start and Step values are optional. When only stop value given, the numerical range is generated from 0 to stop value with step 1.
  • The dtype specifies the datatype for the numpy array.
  • If you given start and stop value it generates the numerical range of values from start value to stop value with step 1.
  • If you give start,stop and step value, it generates the range from start value to stop with the given step value. 


1.  Creating numpy array using arange() method.


Creating One Dimensional array using arange method :

import numpy as np
# creating ndarray with stop attribute
array1=np.arange(5)
print(array1)
# creating ndarray with start and stop attribute
array2=np.arange(2,10)
print(array2)
# creating ndarray with start,stop and step attribute
array2=np.arange(2,10,2)
print(array2)
# creating ndarray with start,stop,step and count attribute
array2=np.arange(2,10,2,dtype=np.float32)
print(array2)




arange function in python

Remember that we cannot create multi dimensional array or 2 Dimensional array with arange() function directly. For creating 2 dimensional array we have to use reshape() method.


Creating 2 Dimensional array using arange method :

first we have to create 1 D array  as :


import numpy as np

# creating ndarray with start attribute
array1=np.arange(10)
print(array1)

# creating 2 D array
ar1=array1.reshape(5,2)
print(ar1)

# creating ndarray with start and stop attribute
array2=np.arange(1,11)
print(array2)

# creating 2 D array
ar2=array2.reshape(2,5)
print(ar2)

# creating ndarray with start,stop and step attribute
array3=np.arange(2,10,2)
print(array3)

# creating 2 D array
ar3=array3.reshape(2,2)
print(ar3)

# creating ndarray with start,stop,step and count attribute
array4=np.arange(2,10,2,dtype=np.float32)
print(array4)

# creating 2 D array
ar4=array4.reshape(2,2)
print(ar4)



arange function uses reshape method


reshape method in python numpy


Here remember one thing is that the shape of originally created ndarray using arange() method must be compatible with the new shape that you specify with reshape() function. If you created an ndarray containing 9 elements with arange() method, you can easily reshape it into a 2D  ndarray of 3 X 3 size but you cannot reshape it to 4 x 2  or 5 x 2 shapes as these are not compatible with the original shape.

In other words , the number of elements created ndarray must be the same as that of new 2D ndarray being created through reshape() method.

You can also combine both arange() and reshape() methods in a single statement as :

arr2= np.arange(10).reshape(2,4)

And,

You can also create floating values as elemnets

arr2=np.arange(9.0).reshape(3,3)
print(arr2)

It will give result as

array([[0. 1. 2.],
           [3. 4. 5.],
           [6. 7. 8.]])



Python Strings

No comments:

Post a Comment

Recent Post

Python Project | Banking System | Project on Banking System using python

  PYTHON PROJECT Banking System import csv import pandas as pd import matplotlib.pyplot as plt import sys import datetime found=False def ne...