Python NumPy Tutorial - Indian AI Production https://indianaiproduction.com/python-numpy-tutorial-mastery-in-numpy-library/ Artificial Intelligence Education Free for Everyone Fri, 28 Jun 2019 17:48:18 +0000 en-US hourly 1 https://i0.wp.com/indianaiproduction.com/wp-content/uploads/2019/06/Channel-logo-in-circle-473-x-472-px.png?fit=32%2C32&ssl=1 Python NumPy Tutorial - Indian AI Production https://indianaiproduction.com/python-numpy-tutorial-mastery-in-numpy-library/ 32 32 163118462 NumPy Mathematical Functions – Python NumPy Tutorial https://indianaiproduction.com/numpy-mathematical-functions/ https://indianaiproduction.com/numpy-mathematical-functions/#respond Fri, 28 Jun 2019 17:40:49 +0000 https://indianaiproduction.com/?p=565 Numpy Mathematica Functions The NumPy is the best python library for mathematics. In NumPy Mathematical Functions blog going to learn most useful mathematical functions. NumPy Arithmetic Operations Using Python NumPy functions or operators solve arithmetic operations. To use NumPy need to import it. Note: In this blog, all practical perform on Jupyter Notebook. If you …

NumPy Mathematical Functions – Python NumPy Tutorial Read More »

The post NumPy Mathematical Functions – Python NumPy Tutorial appeared first on Indian AI Production.

]]>
Numpy Mathematica Functions

The NumPy is the best python library for mathematics. In NumPy Mathematical Functions blog going to learn most useful mathematical functions.

NumPy Arithmetic Operations

Using Python NumPy functions or operators solve arithmetic operations.

To use NumPy need to import it.

import numpy as np # import numpy package and np is short name given to it

Note: In this blog, all practical perform on Jupyter Notebook. If you are working on another IDE rather than it. So please assign the return value to any variable and to show it as output using a print() function.

Creating two arrays using np.arange() function and reshape it in 2D using np.reshape() function.

arr1 = np.arange(1,10).reshape(3,3)
arr2 = np.arange(1,10).reshape(3,3)

# print arr1 and arr2
print(arr1)
print(arr2)
Output >>> 
[[1 2 3]
 [4 5 6]
 [7 8 9]]

[[1 2 3]
 [4 5 6]
 [7 8 9]]

Addition of Two Numpy Array

Using + Operator

arr1 + arr2
Output >>>
array([[ 2,  4,  6],
       [ 8, 10, 12],
       [14, 16, 18]])

using np.add() function

np.add(arr1, arr2)
Output >>>
array([[ 2,  4,  6],
       [ 8, 10, 12],
       [14, 16, 18]])

Subtraction of Two NumPy Array

using – Operator

arr1 - arr2
Output >>>
array([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])

Using np.subtract() function

np.subtract(arr1, arr2)
Output >>>
array([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])

Division of Two NumPy Array

using – Operator

arr1 / arr2
Output >>>
array([[1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.]])

Using np.divide() function

np.divide(arr1, arr2)
Output >>>
array([[1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.]])

Multiplication of Two NumPy Array

using * Operator

arr1 * arr2
Output >>>
array([[ 1,  4,  9],
       [16, 25, 36],
       [49, 64, 81]])

Using np.multiply() function

np.multiply(arr1, arr2)
Output >>>
array([[ 1,  4,  9],
       [16, 25, 36],
       [49, 64, 81]])

Matrix Product of Two NumPy Array (matrix)

using @ Operator

arr1 @ arr2
Output >>>
array([[ 30,  36,  42],
       [ 66,  81,  96],
       [102, 126, 150]])

Using np.dot() function

arr1.dot(arr2)
Output >>>
array([[ 30,  36,  42],
       [ 66,  81,  96],
       [102, 126, 150]])

NumPy Mathematical Built-in functions

np.max()

To find maximum value from an array.

arr1.max()
Output >>> 9
arr1.max(axis = 0) # return max value from each column
Output >>> array([7, 8, 9])
arr1.max(axis = 1) # return max value from each row
Output >>> array([3, 6, 9])

np.argmax()

arr1.argmax() # return index of max value of an array
output >>> 8

np.min()

To find minimum value from an array.

arr1.min()
Output >>> 1
arr1.min(axis = 0) # return min value from each column
Output >>> array([1, 2, 3])

np.argmin()

arr1.argmin() # return index of min value of an array
Output >>> 0

np.sum()

Return sumation of NuPy array.

np.sum(arr1)
Output >>> 45
np.sum(arr1, axis = 0) # return sum of each column
Output >>> array([12, 15, 18])
np.sum(arr1, axis = 1) # return sum of each row
Output >>> array([ 6, 15, 24])

np.mean()

Return mean of NumPy array.

np.mean(arr1)
Output >>> 5.0

np.sqrt()

Return square root of each element of NumPy array.

np.sqrt(arr1)
Output >>>
array([[1.        , 1.41421356, 1.73205081],
       [2.        , 2.23606798, 2.44948974],
       [2.64575131, 2.82842712, 3.        ]])

np.std()

Return standerd division of Numpy array.

np.std(arr1)
Output >>> 2.581988897471611

no.exp()

Return exponential value of each element of the NumPy array.

np.exp(arr1)
Output >>> 
array([[2.71828183e+00, 7.38905610e+00, 2.00855369e+01],
       [5.45981500e+01, 1.48413159e+02, 4.03428793e+02],
       [1.09663316e+03, 2.98095799e+03, 8.10308393e+03]])

no.log()

Return natural log of each element of NumPy array.

np.log(arr1)
Output >>> 
array([[0.        , 0.69314718, 1.09861229],
       [1.38629436, 1.60943791, 1.79175947],
       [1.94591015, 2.07944154, 2.19722458]])

np.log10()

Return log to the base 10 value of each element of NumPy array.

np.log10(arr1)
Output >>> 
array([[0.        , 0.30103   , 0.47712125],
       [0.60205999, 0.69897   , 0.77815125],
       [0.84509804, 0.90308999, 0.95424251]])

Conclusion 

In the blog of NumPy mathematical functions, we covered the most useful mathematical functions. These are the best to solve machine learning and data science project. If you want to learn more functions, then jump on the official website of Numpy.

Download Jupyter file of above source code.

The post NumPy Mathematical Functions – Python NumPy Tutorial appeared first on Indian AI Production.

]]>
https://indianaiproduction.com/numpy-mathematical-functions/feed/ 0 565
Python NumPy Tutorial – Mastery with NumPy Array library https://indianaiproduction.com/python-numpy-tutorial/ https://indianaiproduction.com/python-numpy-tutorial/#comments Sun, 16 Jun 2019 13:04:36 +0000 https://indianaiproduction.com/?p=226 In the Python NumPy tutorial will discuss each and every topic of NumPy array python library from scratch. At the end of this tutorial, you will achieve mastery in the NumPy library. What is NumPy? NumPy is a scientific computing package (library) for python programming language. Numpy is a powerful Python programming language library to …

Python NumPy Tutorial – Mastery with NumPy Array library Read More »

The post Python NumPy Tutorial – Mastery with NumPy Array library appeared first on Indian AI Production.

]]>
In the Python NumPy tutorial will discuss each and every topic of NumPy array python library from scratch. At the end of this tutorial, you will achieve mastery in the NumPy library.

What is NumPy?

NumPy is a scientific computing package (library) for python programming language.

Numpy is a powerful Python programming language library to solve numerical problems.

What is the meaning of NumPy word?

Num stands for numerical and Py stands for Python programming language.

Python NumPy library is especially used for numeric and mathematical calculation like linear algebra, Fourier transform, and random number capabilities using Numpy array.

NumPy supports large data in the form of a multidimensional array (vector and matrix).

Prerequisites to learn Python NumPy Library

NumPy Python library is too simple to learn. The basic python programming and its other libraries like Pandas and Matplotlib knowledge will help to solve real-world problems.

Some basic mathematics like vector and metrics are plus point.

Representation of NumPy multidimensional arrays

Python NumPy Tutorial
Fig 1.1 Multidimensional NumPy arrays

The above figure 1.1 shows one dimensional (1D), two dimensional (2D) and three dimensional (3D) NumPy array

One Dimensional NumPy array (1D): It means the collection of homogenous data in a single row (vector).

Two Dimensional NumPy arrays (2D): It means the collection of homogenous data in lists of a list (matrix).

Three Dimensional NumPy arrays (3D): It means the collection of homogenous data in lists of lists of a list (tensor).

Why NumPy array instead of Python List ?

If you observe in Fig 1.1. To create a NumPy array used list. NumPy array and Python list are both the most similar. NumPy has written in C and Python. That’s a reason some special advantage over Python list is given below.

  • Faster
  • Uses less memory to store data.
  • Convenient.

Why use NumPy for machine learning, Deep Learning, and Data Science?

Python NumPy Tutorial for machine learning data science
Fig 1.2 NumPy for Machine Learning

To solve computer vision and MRI, etc. So for that machine learning model want to use images, but the ML model can’t read image directly. So need to convert image into numeric form and then fit into NumPy array. which is the best way to give data to the ML model.

Fig 1.3 NumPy for Machine Learning

Machine Learning model also used to solve business problems. But we can’t provide ‘.tsv’, ‘.csv’ files data to the ML model, So for that also need to use NumPy array.


In python NumPy tutorial at this movement, we have learned about Python NumPy Library theoretically but its time to do practicals.

Practical Session of Python NumPy Tutorial

How to install Python NumPy Library (package)?

To use the NumPy package first of all need to install it.

If you installed Anaconda Navigator and launched Jupyter Notebook or Spyder then no need to install NumPy. Anaconda Navigator installed NumPy itself. If you are using another IDE instead of Anaconda Navigator then follow below command in command prompt or terminal to install Python NumPy Library (Package).

pip install numpy

While entering the above command, your system has an internet connection because ‘pip’ package download ‘numpy’ package and then install it. After successful installation, You are ready to take the advantages of the NumPy package.


How to import NumPy Library in IDE or How to use it?

To use NumPy first import it. For import NumPy, follows below syntax in the python program file.

import numpy as np
  • import: import keyword imports the NumPy package in the current file.

  • as:  as is a keyword used to create sort name of NumPy.

  • np: np is a short name given to NumPy, you can give any name (identifier) instead of it. If we use NumPy name in the program repeatedly so it will consume typing time and energy as well so for that we gave a short name for our convenience.

Flow the below syntax to create NumPy ndarray (multidimensional array)

How to create one dimensional NumPy array?

To create python NumPy array use array() function and give items of a list.

Syntax: numpy.array(object, dtype=None, copy=True, order=’K’, subok=False, ndmin=0)

import numpy as np # import numpy package
one_d_array = np.array([1,2,3,4]) # create 1D array
print(one_d_array) # printing 1d array
Output >>> [1 2 3 4]

How to create two dimensional NumPy array?

To create 2D array, give items of lists in list to NumPy array() function.

import numpy as np # impoer numpy package
two_d_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # create 1D array
print(two_d_array) #printing 2D array
Ootput >>> [[1 2 3]
            [4 5 6]
            [7 8 9]]

In this way, you can create NumPy ndarray

Let’s going forward to learn more in python NumPy tutorial.

How to check the type of ndarray?

The type() function give the type of data.

Syntax: type(self, /, *args, **kwargs)

type(one_d_array) # give the type of data present in one_d_array variable
Output >>> numpy.ndarray
How to check dimension of NumPy ndarray?

The ndim attribute help to find the dimension of any NumPy array.

Syntax: array_name.ndim

one_d_array.ndim # find the dimension of one_d_array
Output >>> 1

1 value represent, one_d_array array has one dimension.

How to check the size of the NumPy array?

The size attribute help to know, how many items present in a ndarray.

Syntax: array_name.size

one_d_array.size
Output >>> 4

4 value represent, total 4 item present in the one_d_array.

How to check the shape of ndarray?

The shape attribute help to know the shape of NumPy ndarray. It gives output in the form of a tuple data type. Tuple represents the number of rows and columns. Ex: (rows, columns)

Syntax: array_name.shape

two_d_array.shape
Output >>> (3, 3)

The two_d_array has 3 rows and 3 columns.

How to the data type of NumPy ndarray?

The dtype attribute help to know the data type of ndarray.

Syntax: array_name.dtype

one_d_array.dtype
dtype('int32')

As per the above output one-d_array contain integer type data. This data store in 32 bit format (4 byte).

Up to here you can create and know about NumPy ndarray in python NumPy tutorial. Let’s know more something interesting.

Create metrics using python NumPy functions 

Ones metrics use NumPy ones() function.

Syntax: np.ones(shape, dtype=None, order=‘C’)

np.ones((3,3), dtype = int)
Output >>>
array([[1, 1, 1],
       [1, 1, 1],
       [1, 1, 1]])

Zeros metrics use NumPy zeros() function.

Syntax: np.zeros(shape, dtype=None, order=‘C’)

np.zeros((3, 3), dtype = int)
Output >>>
array([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])

Empty metrics use NumPy empty() function.

Syntax: np.empty(shape, dtype=None, order=‘C’)

np.empty((2,4))
Output >>>
array([[0.00000000e+000, 0.00000000e+000, 0.00000000e+000, 0.00000000e+000],
       [0.00000000e+000, 6.42285340e-321, 8.70018274e-313,6.95271921e-310]])

By default NumPy empty() function give float64 bit random value. According to your requirement change dtype.

Create NumPy 1D array using arange() function

Syntax: np.arange([start,] stop[, step,], dtype=None)

arr = np.arange(1,13)
print(arr)
Output >>> [ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12]

Create NumPy 1D array using linspace() function

Return evenly spaced numbers over a specified interval.

Syntax: np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0,)

np.linspace(1,5,4)
Output >>> array([1.        , 2.33333333, 3.66666667, 5.        ])

Convert 1D array to multidimensional array using reshape() function

Syntax: np.reshape(a, newshape, order=‘C’)

arr_reshape = np.reshape(arr, (3,4))
print(arr_reshape)
Output >>> 
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]

Convert multidimensional array in one dimensional

To convert multidimensional array into 1D use ravel() or flatten() function.

Syntax: np.ravel(array_name, order=‘C’)  or  array_name.ravel(order=‘C’)

               array_name.flatten(order=‘C’)

arr_reshape.flatten()
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])

Transpose metrics

Syntax: np.transpose(array_name, axes=Noneor

                array_name.T

Output >>>
array([[ 1,  5,  9],
       [ 2,  6, 10],
       [ 3,  7, 11],
       [ 4,  8, 12]])

Conclusion

I hope, you learn each and every topic of python NumPy tutorial. This all topics important to do the project on machine learning and data science. Apart from the above-explained NumPy methods and operators, you can learn from numpy.org. This is an official website of python NumPy library. If you have fined any mistake in this tutorial of suggestions mention in the comment box. 

The post Python NumPy Tutorial – Mastery with NumPy Array library appeared first on Indian AI Production.

]]>
https://indianaiproduction.com/python-numpy-tutorial/feed/ 5 226
NumPy String Operations | Python NumPy Tutorial https://indianaiproduction.com/numpy-string-operations/ https://indianaiproduction.com/numpy-string-operations/#respond Sun, 16 Jun 2019 12:14:49 +0000 https://indianaiproduction.com/?p=377 If you want to work on string data then NumPy string operations methods help to do work easy. The python NumPy support a bunch of string operations, string comparison, and string information methods. So lets start with Python NumPy String Operations Methods To start the use of string methods need to import NumPy package and …

NumPy String Operations | Python NumPy Tutorial Read More »

The post NumPy String Operations | Python NumPy Tutorial appeared first on Indian AI Production.

]]>
If you want to work on string data then NumPy string operations methods help to do work easy. The python NumPy support a bunch of string operations, string comparison, and string information methods.

So lets start with

Python NumPy String Operations Methods

To start the use of string methods need to import NumPy package and some raw string data.

import numpy as np # import numpy package
ch_name = "Indian AI Production" # create string
str1 = "Learning Python NumPy" # create string

np.char.add()

This function use to add two strings.

Syntax: np.char.add(string_array1, string_array2)

add_string = np.char.add(ch_name, str1) # add two strings ch_name and str1
print("Added two string ch_name and str1 = ", add_string)
Output >>> Added two string ch_name and str1 =  Indian AI ProductionLearning Python NumPy

Click here to jump on python NumPy tutorial.

np.char.multiply()

This function helps to duplicate string required number of times.

Syntax: np.char.multiply(string_array, number)

duplicate_ch_name = np.char.multiply(ch_name, 2) # multiply ch_name 2 times
print("Duplicated ch_name = ", duplicate_ch_name) # print duplicate_ch_name 
Output >>> Duplicated ch_name =  Indian AI ProductionIndian AI Production

np.char.capitalize()

The capitalize() function convert given string’s first character in capital format.

Syntax: np.char.capitalize(string_array)

cap_ch_name = np.char.capitalize(ch_name) # capital ch_name
print("Capitalize ch_name = ", cap_ch_name) # print cap_ch_name 
Output >>> Capitalize ch_name =  Indian ai production

np.char.lower()

The lower() function convert given string in lower case..

Syntax: np.char.lower(string_array)

low_ch_name = np.char.lower(ch_name) # lower ch_name
print("Lower ch_name = ", low_ch_name) # print ch_name
Output >>> Lower ch_name =  indian ai production

np.char.upper()

The upper() function convert given string in upper case..

Syntax: np.char.upper(string_array)

upp_ch_name = np.char.upper(ch_name) # upper ch_name
print("Upper ch_name = ", upp_ch_name) # print upp_ch_name
Output >>> Upper ch_name =  INDIAN AI PRODUCTION

np.char.title()

The title() function convert given string in title format..

Syntax: np.char.title(string_array)

tit_upp_ch_name = np.char.title(upp_ch_name) # title upp_ch_name
print("Title upp_ch_name = ", tit_upp_ch_name) # print tit_upp_ch_name
Output >>> Title upp_ch_name =  Indian Ai Production

np.char.center()

The title() function set the ng in the center of given string length. If you want to fill the ng’s side black space. Then give fillchar parameter with character.

Syntax: np.char.center(string_array, width, fillchar=‘ ‘)

cen_ch_name = np.char.center(ch_name, 30, fillchar = "*") # center upp_ch_name
print("Center ch_name = ", cen_ch_name) # print cen_ch_name
Output >>> Center cen_ch_name =  *****Indian AI Production*****

np.char.split()

The split() function split the string in a list of items. By default split function split the string by space.

Syntax: np.char.split(string_array, sep=None, maxsplit=None)

spl_ch_name = np.char.split(ch_name) # split ch_name
print("Split spl_ch_name = ", spl_ch_name) # print spl_ch_name
Output >>> Split ch_name =  ['Indian', 'AI', 'Production']

np.char.splitlines()

The splitlines() function split the string by lines in a list as elements.

Syntax: np.char.splitlines(string_array, keepends=None)

splitlines_str = np.char.splitlines("Indian\nAi\nProduction") # splitlines string
print("Splitlines  = ", splitlines_str ) # print splitlines_str 
Output >>> Splitlines  =  ['Indian', 'Ai', 'Production']

np.char.join()

The join() function join the echa character of given sequence by seperator.

Syntax: np.char.join(string_array_seperator, string_array)

join_dmy = np.char.join([":", "/"], ["dmy", "dmy"])
print("Joint dmy by : and / = ", join_dmy)
Output >>> Joint dmy by : and / =  ['d:m:y' 'd/m/y']

np.char.replace()

The replace() function replace existing string by new given string.

Syntax: np.char.replace(string_array, old_string_array, new_string_array, count=None)

# Replace "AI" by "Artificial Intelligence" from ch_name
rep_ch_name = np.char.replace(ch_name, "AI", "Artificial Intelligence")
print("Replace old string by new = ", rep_ch_name)
Output >>> Replace old string by new =  Indian Artificial Intelligence Production

Python NumPy String Comparison 

The string comparison methods use to compare string with each other and return a boolean value.

np.char.equal()

The equal() function return “True” boolean value, If both strings are same else “False”.

Syntax: np.char.equal(string_array1,  string_array2)

or use equal to operator

string_array1 == string_array2

equ_str = np.char.equal(ch_name, str1) # check equality
print("Is ch_name equal to str1 = ", equ_str ) 
Output >>> Is ch_name equal to str1 =  False

np.char.not_equal()

The not_equal() function return “True” boolean value, If both strings are not same else “False”.

Syntax: np.char.not_equal(string_array1,  string_array2)

or use equal to operator

string_array1 != string_array2

not_equ_str = np.char.equal(ch_name, str1) # check  non equality
print("Is ch_name not equal to str1 = ", equ_str ) 
Output >>> Is ch_name not equal to str1 =  False

Python NumPy string Information

The string information methods use to get information from the stings.

np.char.count()

The count() function count string from an existing string and return number.

Syntax: np.char.count(string_array, sub, start=0, end=None)

count_A = np.char.count(ch_name, "A") # count string "A"
print("Character 'A' present ", count_A , " times in a string - ", ch_name) 
Output >>> Character 'A' present  1  times in a string -  Indian AI Production

np.char.find()

The find() function find given string from an existing string and return the index of the first character of that string.

Syntax: np.char.find(string_array, sub, start=0, end=None)

find_AI = np.char.count(ch_name, "AI") # Find string "AI"
print("String  'AI' found at index ", find_AI , " from string - ", ch_name) 
Output >>> String  'AI' found at index  1  from string -  Indian AI Production

np.char.index()

The index() function find an index of a given string from an existing string and return the index of the first character of that string. If string will not found then return ValueError.

Syntax: np.char.index(string_array, sub, start=0, end=None)

index_AI = np.char.index(ch_name, "m") # Find index "m"
print("Index of 'm' string found at - ", find_AI , " from string - ", ch_name) 

Output >>> 

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-55-f70fbeb5e5eb> in <module>
----> 1 index_AI = np.char.index(ch_name, "m") # Find index "m"
      2 print("Index of 'm' string found at - ", find_AI , " from string - ", ch_name)

~\Anaconda3\lib\site-packages\numpy\core\defchararray.py in index(a, sub, start, end)
    680     """
    681     return _vec_string(
--> 682         a, integer, 'index', [sub, start] + _clean_args(end))
    683 
    684 def isalnum(a):

ValueError: substring not found

np.char.isalpha()

The isalpha() function return “True”. If the string contains each and every character are the alphabet.

Syntax: np.char.isalpha(string_array)

str_isalpha = np.char.isalpha("Hello") 
print("Is String 'Hello' alphabet - ", str_isalpha ) 
Output >> Is String 'Hello' alphabet -  True

np.char.isdecimal()

The isdecimal() function return “True”. If the string contains each and every character are decimal.

Syntax: np.char.isdecimal(string_array)

str_isdecimal = np.char.isdecimal("Hello") 
print("Is String 'Hello' decimal - ", str_isdecimal )
Output >>> Is String 'Hello' decimal -  False

np.char.isdigit()

The isdigit() function return “True”. If the string contains each and every character are digits.

Syntax: np.char.isdigit(string_array)

str_isdigit = np.char.isdigit("Hello") 
print("Is String 'Hello' digit - ", str_isdigit )
Output >>> Is String 'Hello' digit -  False

np.char.islower()

The islower() function return “True”. If string contain each and every character in lowercase.

Syntax: np.char.islower(string_array)

str_islower = np.char.islower("Hello") 
print("Is String 'Hello' lower - ", str_islower )
Output >>> Is String 'Hello' lower -  False

np.char.isupper()

The isupper() function return “True”. If string contain each and every character in uppercase.

Syntax: np.char.isupper(string_array)

str_isupper = np.char.isupper("Hello India") 
print("Is String 'Hello India' uppercase - ", str_isupper )
Output >>> Is String 'Hello India' uppercase -  False

np.char.isnumeric()

The isnumeric() function return “True”. If string contain each and every character in numeric form.

Syntax: np.char.isnumeric(string_array)

str_isnumeric = np.char.isnumeric("Hello") 
print("Is String 'Hello' numeric - ", str_isnumeric )
Output >>> Is String 'Hello' numeric -  False

np.char.isspace()

The isspace() function return “True”. If string contain black space.

Syntax: np.char.isspace(string_array)

str_isspace = np.char.isspace("Hello India") 
print("Is String 'Hello India' space - ", str_isspace )
Output >>> Is String 'Hello India' space -  False

To learn more about Python NumPy in detail click below button.

Click here to refer or learn more methods on official site of scipy.org.

Conclusion

The python NumPy string operations have a number of methods and remember that method is a bit difficult. So don’t worry this all methods newer ever use in your professional life. If you want to use it refer to this blog. 

The post NumPy String Operations | Python NumPy Tutorial appeared first on Indian AI Production.

]]>
https://indianaiproduction.com/numpy-string-operations/feed/ 0 377
Numpy random | random module |Python Numpy Tutorial https://indianaiproduction.com/numpy-random/ https://indianaiproduction.com/numpy-random/#respond Sat, 15 Jun 2019 07:19:05 +0000 https://indianaiproduction.com/?p=373 Python NumPy random module The NumPy random is a module help to generate random numbers. Import NumPy random module np.random.random() This function generates float value between 0.0 to 1.0 and returns ndarray if you will give shape. Click here to jump on Python NumPy tutorial np.random.randint() The random integer function generates single random integer number …

Numpy random | random module |Python Numpy Tutorial Read More »

The post Numpy random | random module |Python Numpy Tutorial appeared first on Indian AI Production.

]]>
Python NumPy random module

The NumPy random is a module help to generate random numbers.

Import NumPy random module

import numpy as np # import numpy package
import random # import random module

np.random.random()

This function generates float value between 0.0 to 1.0 and returns ndarray if you will give shape.

rd_num = np.random.random(1)
rd_2D_array =  np.random.random((3,3))
print(rd_num)
print(rd_2D_array)
Output >>>
[0.4698348]

[[0.17440905, 0.66151053, 0.66339827],
 [0.88763943, 0.8709484 , 0.06250261],
 [0.09760232, 0.05503074, 0.55680254]]

Click here to jump on Python NumPy tutorial

np.random.randint()

The random integer function generates single random integer number from given range and if the shape will give then return ndarray.

rd_no = np.random.randint(1,4)
rd_2D_arr = np.random.randint(1,4, (4,4))
rd_3D_arr = np.random.randint(1,4, (2,4,4))

print(rd_no)
print(rd_2D_arr)
print(rd_3D_arr)

np.random.seed()

The random module generates random number but next time you want to generate the same number then seed() will help.

np.random.seed(10)
rd_3D_arr = np.random.randint(1,4, (2,4,4))
print(rd_3D_arr)
Output >>>
      [[[2, 2, 1, 1],
        [2, 1, 2, 2],
        [1, 2, 2, 3],
        [1, 2, 1, 3]],

       [[1, 3, 1, 1],
        [1, 3, 1, 3],
        [3, 2, 1, 1],
        [3, 2, 3, 2]]]

Nex time generate the same 3D array using the same seed value (10).

np.random.seed(10)
rd_3D_arr = np.random.randint(1,4, (2,4,4))
print(rd_3D_arr)
Output >>>
      [[[2, 2, 1, 1],
        [2, 1, 2, 2],
        [1, 2, 2, 3],
        [1, 2, 1, 3]],

       [[1, 3, 1, 1],
        [1, 3, 1, 3],
        [3, 2, 1, 1],
        [3, 2, 3, 2]]]

Note: The seed function accepts value up to  2^32 -1 (4294967295).

np.random.rand()

The rand() function work like random() but it accept shape and return ndarray which contain random values between 0.0 to 1.0.

arr_2D = np.random.rand(3,3) # return  3 x 3 matrix
print(arr_2D)
Output >>>
      [[0.58390137, 0.18263144, 0.82608225],
       [0.10540183, 0.28357668, 0.06556327],
       [0.05644419, 0.76545582, 0.01178803]]

np.random.randn()

The randn() function work like rand() function but it reurn samples of  standerd normalise distribution value.

arr_2D = np.random.randn(3,3)
print(arr_2D)
Output >>>
      [[-1.58494101,  1.05535316, -1.92657911],
       [ 0.69858388, -0.74620143, -0.15662666],
       [-0.19363594,  1.13912535,  0.36221796]]

np.random.choice()

If you have sequence values and want to get random single value then the random choice() function is the best choice.

x = [1,2,3,4] # list
choice_from_x = np.random.choice(x) # retun random single item from sequence
print(choice_from_x )
Output >>>
1

Let’s try to get the number of choice from sequence x using for loop.

for i in range(20):
    print(np.random.choice(x))
Output >>>
2
1
4
1
1
3
1
3
3
1
4
2
1
4
2
3
3
2
3
3

np.random.permutation()

If you want to generate some permutation of sequence then use random permutation() function.

x_permute = np.random.permutation(x)
print(x_permute)
Output >>> 
[2, 3, 4, 1]

Learn more about random sampling then click here

The post Numpy random | random module |Python Numpy Tutorial appeared first on Indian AI Production.

]]>
https://indianaiproduction.com/numpy-random/feed/ 0 373
Python NumPy shape – Python NumPy Tutorial https://indianaiproduction.com/python-numpy-shape/ https://indianaiproduction.com/python-numpy-shape/#comments Fri, 14 Jun 2019 09:52:20 +0000 https://indianaiproduction.com/?p=359 Python NumPy array shape Function The NumPy shape function helps to find the number of rows and columns of python NumPy array. The numpy.shape() function gives output in form of tuple (rows_no, columns_no).  Syntax: np.shape(array) The shape of a Numpy 1D array When you will find the shape of NumPy one dimensional array then np.shape() …

Python NumPy shape – Python NumPy Tutorial Read More »

The post Python NumPy shape – Python NumPy Tutorial appeared first on Indian AI Production.

]]>
Python NumPy array shape Function

The NumPy shape function helps to find the number of rows and columns of python NumPy array. The numpy.shape() function gives output in form of tuple (rows_no, columns_no). 

Syntax: np.shape(array)

NumPy shape

The shape of a Numpy 1D array

import numpy as np # import numpy package
arr_1D = np.array([1, 2, 3]) # create 1D array
print("One dimentional NumPy array : \n", arr_1D) # print arr_1D

shape_of_arr_1D = np.shape(arr_1D) # find shape of NumPy Array arr_1D
print("Shape of arr_1D = ", shape_of_arr_1D) # print shape_of_arr_1D
Output >>>

One dimentional NumPy array : 
 [1 2 3]
Shape of arr_1D =  (3,)

When you will find the shape of NumPy one dimensional array then np.shape() give a tuple which contains a single number. That number shows the column number respected to the array.

The shape of a Numpy 2D array

arr_2D = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) # create 2D array
print("Two array : \n", arr_2D) # print arr_2D

shape_of_arr_2D = np.shape(arr_2D) # find shape of NumPy array arr_2D
print("Shape of arr_2D = ", shape_of_arr_2D) # print shape_of_arr_2D
Output >>> 

Two array : 
 [[1 2 3]
  [1 2 3]
  [1 2 3]]
Shape of arr_2D =  (3, 3)

The np.shape() gives a return of two-dimensional array in a  pair of rows and columns tuple (rows, columns).

The shape of a Numpy 3D array

arr_3D = np.array([[[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]]]) # create 3D array
print("Three dimensional NumPy Array : \n", arr_3D)

shape_of_arr_3D = np.shape(arr_3D) # find shape of NumPy array arr_3D
print("Shape of arr_3D = ", shape_of_arr_3D) # print shape_of_arr_3D
Output >>>

Three dimensional NumPy Array : 
[[[1 2 3]
  [1 2 3]
  [1 2 3]]

 [[1 2 3]
  [1 2 3]
  [1 2 3]]

 [[1 2 3]
  [1 2 3]
  [1 2 3]]] 
Shape of arr_3D =  (3, 3, 3)

The np.shape() gives a return of three-dimensional array in a  tuple (no. of 2D arrays, rows, columns).

Python NumPy array shape using shape attribute

Above you saw, how to use numpy.shape() function. Instead of it, you can use Numpy array shape attribute.

Syntax: array.shape

shape_of_arr_1D = arr_1D.shape # return shape of arr_1D
print("Shape of 1D array = ", shape_of_arr_1D)
 Output >>> Shape of 1D array =  (3,)

Python NumPy array shape vs size

Most of the people confused between both functions. NumPy array shape gives the shape of a NumPy array and Numpy array size function gives the size of a NumPy array.

Click here to learn more about Numpy array size.

 

Question: Find the shape of below array and print it.

student_info = np.array([['id', 'name', 'percentage', 'pass or fail'], 
                     [101, 'Ajay', 80, 'pass'], 
                     [102, 'John', 75, 'pass'],
                     [103, 'Abraham',33, 'fail'],
                     [104, 'Oprah',52, 'pass']
                    ])

Solution:

shape_of_student_info = np.shape(student_info)
print("Shape of student information array = ", shape_of_student_info)
Output >>> Shape of student information array =  (5, 4)

To learn more about python NumPy library click on the bellow button.

The post Python NumPy shape – Python NumPy Tutorial appeared first on Indian AI Production.

]]>
https://indianaiproduction.com/python-numpy-shape/feed/ 1 359
NumPy array size – np.size() | Python NumPy Tutorial https://indianaiproduction.com/numpy-array-size/ https://indianaiproduction.com/numpy-array-size/#respond Fri, 14 Jun 2019 06:08:37 +0000 https://indianaiproduction.com/?p=334 To find python NumPy array size use size() function. The NumPy size() function has two arguments. First is an array, required an argument need to give array or array name. Second is an axis, default an argument. The axis contains none value, according to the requirement you can change it. The np.size() function count items …

NumPy array size – np.size() | Python NumPy Tutorial Read More »

The post NumPy array size – np.size() | Python NumPy Tutorial appeared first on Indian AI Production.

]]>
To find python NumPy array size use size() function. The NumPy size() function has two arguments. First is an array, required an argument need to give array or array name. Second is an axis, default an argument. The axis contains none value, according to the requirement you can change it.

The np.size() function count items from a given array and give output in the form of a number as size. 

Syntax: np.size(array, axis=None)

NumPy Array Size

import numpy as np # import numpy package

arr_2D = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]]) # create NumPy 2D array
print("2D array : \n", arr_2D) # print array

array_size = np.size(arr_2D) # find the size of arr-2D

print('Size of arr_2D = ', array_size) # print size of array
Output >>>

2D array : 
 [[0 1 1]
 [1 0 1]
 [1 1 0]]

Size of arr_2D =  9

If you want to count how many items in a row or a column of NumPy array. Then give the axis argument as 0 or 1.

items_in_col = np.size(arr_2D, axis = 0) # give columns 
print("No. of items in a column = ", items_in_col )

items_in_row = np.size(arr_2D, axis = 1)
print("No. of items in a row = ", items_in_row )
Output >>> 
No. of items in a column =  3
No. of items in a row =  3

You can find the size of the NumPy array using size attribute.

Syntax: array.size

print("Size of arr_2D = ", arr_2D.size)
Output >>> Size of arr_2D =  9

To learn more about python NumPy library click on the bellow button.

The post NumPy array size – np.size() | Python NumPy Tutorial appeared first on Indian AI Production.

]]>
https://indianaiproduction.com/numpy-array-size/feed/ 0 334
NumPy Trigonometric Functions – np.sin(), np.cos(), np.tan() https://indianaiproduction.com/numpy-trigonometric-functions/ https://indianaiproduction.com/numpy-trigonometric-functions/#comments Thu, 13 Jun 2019 13:41:31 +0000 https://indianaiproduction.com/?p=340 NumPy Trigonometric Functions NumPy supports trigonometric functions like sin, cos, and tan, etc. The NumPy trigonometric functions help to solve mathematical trigonometric calculation in an efficient manner.  np.sin() Trigonometric Function The np.sin() NumPy function help to find sine value of the angle in degree and radian. Syntax: sin(x, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, …

NumPy Trigonometric Functions – np.sin(), np.cos(), np.tan() Read More »

The post NumPy Trigonometric Functions – np.sin(), np.cos(), np.tan() appeared first on Indian AI Production.

]]>
NumPy Trigonometric Functions

NumPy supports trigonometric functions like sin, cos, and tan, etc. The NumPy trigonometric functions help to solve mathematical trigonometric calculation in an efficient manner. 

np.sin() Trigonometric Function

The np.sin() NumPy function help to find sine value of the angle in degree and radian.

Syntax: sin(x, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj])

Sine value of angle in degrees

import numpy as np # import numpy package
sin_90 = np.sin(90) # sine value of degree 90 in degree
print("Sine value of angle 90 in degree = ",sin_90) # print sine value
Output >>>
Sine value of angle 90 in degree =  0.8939966636005579

Sine value of the angle in radians

To get sine value of the angle in radians, need to multiply angle with np.pi/180.

np.pi = 3.14

sin_90 = np.sin(90 * np.pi/180) # sine value of angle 90 in radinas
print("Sine value of angle 90 in radians = ", sin_90)
Output >>>
Sine value of angle 90 in radians =  1.0

Learn more about python NumPy click here.

np.cos() Trigonometric Function

The np.cos() NumPy function help to find cosine value of the angle in degree and radian.

Syntax: cos(x, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj])

Cosine value of angle in degrees

import numpy as np # import numpy package
cos_180 = np.cos(180) # cosine value of degree 180 in degree
print("Cosine value of angle 180 in degree = ", cos_180) # print cosine value
Output >>>
Cosine value of angle 180 in degree =  -0.5984600690578581

Cosine value of the angle in radians

To get cosine value of the angle in radians, need to multiply angle with np.pi/180.

np.pi = 3.14

cos_180 = np.cos(180 * np.pi/180)
print("Cosine value of angle 180 in radians = ", cos_180)
Output >>>
Cosine value of angle 180 in radians =  -1.0

np.tan() Trigonometric Function

The np.tan() NumPy function help to find tangent value of the angle in degree and radian.

Syntax: tan(x, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj])

Tangent value of angle in degrees

import numpy as np # import numpy package
tan_60 = np.tan(60) # tangent value of degree 60 in degree
print("Tangent value of angle 60 in degree = ", tan_60) # print tangent value
Output >>>
Tangent value of angle 60 in degree =  0.320040389379563

Cosine value of the angle in radians

To get the tangent value of the angle in radians, need to multiply angle with np.pi/180.

np.pi = 3.14

tan_60 = np.tan(60 * np.pi/180) # tangent value of degree 60 in degree
print("Tangent value of angle 60 in radians = ", tan_60) # print tangent value
Output >>>
Tangent value of angle 60 in radians =  1.7320508075688767

Graphical Representation of Trigonometric sine Function

import numpy as np # import numpy package
import matplotlib.pyplot as plt # import matplotlib.pyplot package
x = np.arange(0, 3 * np.pi, 0.1) # create x array of angels from range 0 to 3*3.14
y = np.sin(x) # create y array of sine values of angles from x array
plt.plot(x, y) # plot grah 
plt.title(" Graphical Representation of sine function")
plt.xlabel("x axis ")
plt.ylabel("y axis ")
plt.show() # show plotted graph

Output >>>

numpy trigonometric functions Graph
Graph of np.sin() function

Graphical Representation of Trigonometric Cosine Function

import numpy as np # import numpy package
import matplotlib.pyplot as plt # import matplotlib.pyplot package
x = np.arange(0, 3 * np.pi, 0.1) # create x array of angels from range 0 to 3*3.14
y = np.cos(x) # create y array of sine values of angles from x array
plt.plot(x, y) # plot grah 
plt.title(" Graphical Representation of cosine function")
plt.xlabel("x axis ")
plt.ylabel("y axis ")
plt.show() # show plotted graph

Output >>>

NumPy trigonometric functions graph
Graph of np.cos() function

Graphical Representation Of Trigonometric Tangent Function

import numpy as np # import numpy package
import matplotlib.pyplot as plt # import matplotlib.pyplot package
x = np.arange(0, 3 * np.pi, 0.1) # create x array of angels from range 0 to 3*3.14
y = np.tan(x) # create y array of sine values of angles from x array
plt.plot(x, y) # plot grah 
plt.title(" Graphical Representation of tangent function")
plt.xlabel("x axis ")
plt.ylabel("y axis ")
plt.show() # show plotted graph

Output >>>

NumPy trigonometric functions graph
Graph of np.tan() function

Note: To get the value of Numpy trigonometric functions, need to multiply angle value with np.pi/180 because all trigonometric functions accept  by default value as degrees.

Conclusions 

In NumPy trigonometric function blog, We learn how to use np.sin(), np.cos() and np.tan() mathematical trigonometric functon. According to your requirement give argument as degrees or radians value to respective function.

To learn more about python NumPy library click on the bellow button.

The post NumPy Trigonometric Functions – np.sin(), np.cos(), np.tan() appeared first on Indian AI Production.

]]>
https://indianaiproduction.com/numpy-trigonometric-functions/feed/ 3 340
Python NumPy array – Create NumPy ndarray (multidimensional array) https://indianaiproduction.com/python-numpy-array/ https://indianaiproduction.com/python-numpy-array/#comments Wed, 12 Jun 2019 11:42:10 +0000 https://indianaiproduction.com/?p=312 What is the NumPy array? Python NumPy array is a collection of a homogeneous data type. It is most similar to the python list. You can insert different types of data in it. Like integer, floating, list, tuple, string, etc. To create a multidimensional array and perform a mathematical operation python NumPy ndarray is the best …

Python NumPy array – Create NumPy ndarray (multidimensional array) Read More »

The post Python NumPy array – Create NumPy ndarray (multidimensional array) appeared first on Indian AI Production.

]]>
What is the NumPy array?

Python NumPy array is a collection of a homogeneous data type. It is most similar to the python list. You can insert different types of data in it. Like integer, floating, list, tuple, string, etc.

To create a multidimensional array and perform a mathematical operation python NumPy ndarray is the best choice. The ndarray stands for N-Dimensional arrays.

NumPy array
              Fig 1.1 Representation of NumPy ndarray (multidimensional array )

Let’s jump on practical session NumPy


Create NumPy ndarray (1D array)

To create NumPy 1D array use array() function and give one argument of items of a list to it.

Syntax: array(object, dtype=None, copy=True, order=’K’, subok=False, ndmin=0)

import numpy as np # import numpy package
arr_1D = np.array([2,4,6,8]) # create  NumPy 1D array which contain int value 2,4,6,8
print(arr_1D) # print arr_1D
Output >>> [2 4 6 8]

In machine learning and data science NumPy 1D array known as vector. Specially use to store and perform an operation on target values.

Create NumPy ndarray (2D array)

To create NumPy 2D array use array() function and give one argument of items of lists of the list to it.

Syntax: array(object, dtype=None, copy=True, order=’K’, subok=False, ndmin=0)

import numpy as np # import numpy package
arr_2D = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]]) # Create Numpy 2D array which contain inter type valye
print(arr_2D) # print arr_1D
Output >>>

[[0 1 1]
 [1 0 1]
 [1 1 0]]

In machine learning and data science NumPy 2D array known as a matrix. Specially use to store and perform an operation on input values.

Create NumPy ndarray (3D array)

To create NumPy 3D array use array() function and give one argument of items of lists of lists of the list to it.

Syntax: array(object, dtype=None, copy=True, order=’K’, subok=False, ndmin=0)

import numpy as np
arr_3D = np.array([[[0, 1, 1], [1, 0, 1], [1, 1, 0]]]) # create numpy 3D array which contain integer values
print(arr_3D)
Output >>>
 
[[[0 1 1]
  [1 0 1]
  [1 1 0]]]

In machine learning and data science NumPy 3D array known as a tensor. Specially used to store and perform an operation on three-dimensional data like color image.

 

How to store different types of data in NumPy ndarray?

The array() function accepts different types of data. You can insert it while creating an array.

import numpy as np
# store student information in NumPy 2D array
student_info = np.array([['id', 'name', 'percentage', 'pass or fail'], 
                         [101, 'Narendra', 80, 'pass'], 
                         [102, 'John', 75, 'pass'],
                         [103, 'Abraham',33, 'fail'],
                         [104, 'Oprah',52, 'pass']
                        ])
print(student_info)
Output >>> 

[['id' 'name' 'percentage' 'pass or fail']
 ['101' 'Narendra' '80' 'pass']
 ['102' 'John' '75' 'pass']
 ['103' 'Abraham' '33' 'fail']
 ['104' 'Oprah' '52' 'pass']]

How to set default data type?

By default, The python NumPy array data type is none. To set it, give an argument to array() function as the desired data type. like int, float, str, etc.

import numpy as np
percentage = np.array([80, 75, 33, 52], dtype = float) # set data type as float
print(percentage) 
Output >>> [80. 75. 33. 52.]

Generally, remaining default argument of array () function never use but you can try it. In this way, you can create a NumPy multidimensional arrays.

To learn more about python NumPy library click on the bellow button.

The post Python NumPy array – Create NumPy ndarray (multidimensional array) appeared first on Indian AI Production.

]]>
https://indianaiproduction.com/python-numpy-array/feed/ 1 312