Numpy
Numpy
Conten
t
Numpy
NumPy is short for Numerical Python, general-purpose array-processing package. It
provides a high-performance multidimensions
It is the fundamental package for scientific computing with Python.
It is open-source software. It contains various features including these important
ones:
❖ A ndarray, an efficient multi dimensional array providing fast array –oriented
arithmetic operations and flexible broadcasting capabilities
❖ Mathematical functions for fast operations on entire array without having loops.
❖ Tools for reading/writing array data to disk and working with memory-mapped
files.
❖ Useful linear algebra, Fourier transform, and random number capabilities.
❖ A C API for connecting NumPy with libraries written in C,C++, Fortran.
Numpy
Data analysis applications, the main areas of functionality:
Fast vectorized array operations for data munging and cleaning, subsetting
and filtering, transformation, and any other kinds of computations
Common array algorithms like sorting, unique, and set operations
Efficient descriptive statistics and aggregating/summarizing data
Data alignment and relational data manipulations for merging and joining
together heterogeneous data sets
Expressing conditional logic as array expressions instead of loops with
if-elif else branches
Group-wise data manipulations (aggregation,transformation, function
application).
Numpy ndarray: A multidimensional Array Object
1. Arrays in NumPy: NumPy’s main object is the homogeneous multidimensional array.
It is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers.
In NumPy dimensions are called axes. The number of axes is rank.
NumPy’s array class is called ndarray. It is also known by the alias array.
Numpy ndarray: A multidimensional Array
Object
Example :
# Python program to demonstrate basic # Printing shape of array
array characteristics print("Shape of array: ", [Link])
import numpy as np
# Creating array object # Printing size (total number of
arr = [Link]( [[ 1, 2, 3], elements) of array
[ 4, 2, 5]] ) print("Size of array: ", [Link])
array Convert input data (list, tuple, ones, ones_like Produce an array of all 1’s with the
array, or other sequence type) given shape and dtype. ones_like takes
to an ndarray either by inferring another array and produces a ones
a dtype or explicitly specifying a array of the same shape and dtype.
dtype. Copies the input data by
default
Asarray Convert input to ndarray, but zeros, zeros_like Like ones and ones_like but producing
do not copy if the input is arrays of 0’s instead
already an ndarray
Arange Like the built-in range but empty, empty_like Create new arrays by allocating new
returns an ndarray instead of a memory, but do not populate with any
list. values like Create new arrays by
allocating new memory, but do not
populate with any values like
eye, identity Create a square N x N identity
matrix (1’s on the diagonal and
0’s elsewhere)
Datatypes for ndarrays
The data type or dtype is a special object containing the information
the ndarray needs to interpret a chunk of memory as a particular type
of data:
Dtypes are part of what make NumPy so powerful and flexible. In most
cases they map directly onto an underlying machine representation,
which makes it easy to read and write binary streams of data to disk
and also to connect to code written in a low-level language.
The numerical dtypes are named the same way: a type name, like float
or int, followed by a number indicating the number of bits per element.
Datatypes for ndarrays
Example 3
Datatypes for [Link] numpy as np
Example 1 [Link]=[Link]([1.2,-2.1,3.5,4.8])
[Link] numpy as np [Link](np.int32)
2.d = [Link](np.int32) [Link](arr)
[Link](d) Output:
Output: array([1,-2,3,4],dype=int32)
int32 Note:
Example 2 -astype float to int the decimal part will
[Link] numpy as np be truncated
2.d = np.int32(i4) -astype is used to convert string to
[Link](d) numeric form
Output: -astype always create a new array( a
int32 copy of the data), even if newdtype is
same as old dtype.
Arithemetic with NumPy Arrays
Arrays are important because they enables to express batch operations on
data without any loops.
This is called as Vectorization. Any arithmetic operations between equal-size
arrays applies the operation element-wise
Example: Add the values in arr1 to the values in arr2:
import numpy as np
arr1 = [Link]([10, 11, 12, 13, 14, 15])
arr2 = [Link]([20, 21, 22, 23, 24, 25])
newarr = [Link](arr1, arr2)
print(newarr)
Output:
[30 32 34 36 38 40]8 40]
Arithemetic with NumPy Arrays
Example: Subtract the values in arr1 Example: Multiply the values in arr1 to
to the values in arr2: the values in arr2:
import numpy as np import numpy as np
arr1 =[Link]([10, 20, 30, 40, 50, 60]) arr1 =[Link]([10, 20, 30, 40, 50, 60])
arr2= [Link]([20, 21, 22, 23, 24, 25]) arr2= [Link]([20, 21, 22, 23, 24, 25])
newarr = [Link](arr1, arr2) newarr = [Link] (arr1, arr2)
print(newarr) print(newarr)
Output: Output:
[-10 -1 8 17 26 35] [200 420 660 920 1200 1500]
Arithmetic with NumPy Arrays
Reciprocal Function: Returns the reciprocal of all the array elements.
import numpy as np
a = [Link]([7,3,4,5,1])
[Link](a)
Output: array([0,
0, 0, 0, 1])
Power Function: first array as base and raises it to the power of the elements of
the second array.
import numpy as np
a = [Link]([7,3,4,5,1])
b = [Link]([3,4,5,6,7])
[Link](a,b)
Output:array([ 343, 81, 1024, 15625, 1])
Operations between different sized arrays called as Broadcasting
Basic Indexing and Slicing
• Array Indexing: Knowing the basics of array indexing is important for analysing
and manipulating the array object.
• NumPy offers many ways to do array indexing.
• Slicing: Just like lists in python, NumPy arrays can be sliced. As arrays can be
multidimensional, need to specify a slice for each dimension of the array.
• Integer array indexing: In this method, lists are passed for indexing for each
dimension. One to one mapping of corresponding elements is done to construct
a new arbitrary array.
• Boolean array indexing: This method is used when want to pick elements from
array which satisfy some condition.
Basic Indexing and Slicing
• One-dimensional arrays are simple; on the surface they act similarly to Python
lists:
>>>arr = [Link](10)
print(arr)
Output: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>>print (arr[5])
Output: 5
>>> arr[5:8]
print(arr)
Output: array([5, 6, 7])
Basic Indexing and Slicing
>>> arr[5:8] = 12
print(arr)
Output: array([ 0, 1, 2, 3, 4, 12, 12, 12, 8, 9])
• Here assigning a scalar value to a slice, as in arr[5:8] = 12, the value is propagated
(or broadcasted henceforth) to the entire selection. An important first distinction
from lists is that array slices are views on the original array. This means that the
data is not copied, and any modifications to the view will be reflected in the
source.
>>>arr_slice = arr[5:8]
arr_slice[1] = 12345
print( arr)
Output array([ 0, 1, 2, 3, 4, 12, 12345, 12, 8, 9])
Basic Indexing and Slicing
arr_slice[:] = 64
print(arr)
Output:array([ 0, 1, 2, 3, 4, 64, 64, 64, 8, 9])
In a two-dimensional array, the elements at each index are no longer scalars but
rather one-dimensional arrays:
>>>arr2d = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
Print(arr2d[2] )
Output: array([7, 8, 9])
Thus, individual elements can be accessed recursively. But that is a bit too much
work, so can pass a comma-separated list of indices to select individual elements.
Basic Indexing and Slicing
So these are equivalent:
>>> arr2d[0][2]
Output: 3
>>> arr2d[0, 2]
Output: 3