0% found this document useful (0 votes)
3 views16 pages

Num Py

NumPy is an open-source Python library essential for scientific and engineering applications, providing efficient multidimensional array data structures and functions. It excels in handling large homogeneous data sets, offering improved speed and memory efficiency compared to standard Python lists. Key features include array creation, element access, mathematical operations, and reshaping capabilities, making it a powerful tool for numerical computations.

Uploaded by

hitharthkarna
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views16 pages

Num Py

NumPy is an open-source Python library essential for scientific and engineering applications, providing efficient multidimensional array data structures and functions. It excels in handling large homogeneous data sets, offering improved speed and memory efficiency compared to standard Python lists. Key features include array creation, element access, mathematical operations, and reshaping capabilities, making it a powerful tool for numerical computations.

Uploaded by

hitharthkarna
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

NumPy

NumPy (Numerical Python) is an open source Python library that’s widely used in
science and engineering. The NumPy library contains multidimensional array data structures,
such as homogeneous, N-dimensional array, and a large library of functions that operate
efficiently on these arrays.

Why use NumPy?


Python lists are excellent, general-purpose containers. They can be “heterogeneous”,
means that they can contain elements of different types, and they are quite fast when used to
perform individual operations on a handful of elements.
Depending on the characteristics of the data and the types of operations that need to be
performed, other containers may be more appropriate; by exploiting these characteristics, we can
improve speed, reduce memory consumption, and offer a high-level syntax for performing a
variety of common processing tasks. NumPy shines when there are large quantities of
“homogeneous” (same-type) data to be processed.

What is an “array”?
In computer programming, an array is a structure for storing and retrieving data of similar
type. We often talk about an array as if it were contiguous memory cells, with each cell storing
one element of the data. For instance, if each element of the data were a number, we might
visualize a “one-dimensional” array like a list:
1 5 2 0

A two-dimensional array would be like a table:


1 5 2 0
8 3 6 1
1 7 2 9

A three-dimensional array would be like a set of tables, perhaps stacked as though they were
printed on separate pages. In NumPy, this idea is generalized to an arbitrary number of
dimensions, and so the fundamental array class is called ndarray: it represents an “N-
dimensional array”.
Properties of Numpy:
 All elements of the array must be of the same type of data.
 Once created, the total size of the array can’t change.
 The shape must be “rectangular”, not “jagged”; e.g., each row of a two-dimensional array
must have the same number of columns.
When these conditions are met, NumPy exploits these characteristics to make the array faster,
more memory efficient, and more convenient to use than less restrictive data structures.

Array fundamentals:
After importing numpy,
Creating:
Method 1:
<arr_name>=[Link]([<list of elements>],<dtype>)

Example:
Import numpy as np
arr=[Link]([1,2,3,4])
→ dtype is optional

Ex2:
marks=[Link]([100,90,80],dtype=int)
>>>print(marks)
[100 90 80]
>>>type(marks)
<class '[Link]'>
>>>[Link]
dtype('int64')

Few dtypes available: Int, Float, Bool, Complex


Accessing elements:
Elements of an array can be accessed in various ways. For instance, we can access an individual
element of this array as we would access an element in the original list: using the integer index of
the element within square brackets.
a=[Link]([1,2,3,4,5,6])
>>>a[0]
1
>>>a[2]
3
>>>a[0] = 10
>>>a
array([10, 2, 3, 4, 5, 6])

Slicing
Also like the original list, Python slice notation can be used for indexing.
>>>a[:3]
array([10, 2, 3])

List slicing vs NumPy Array Slicing


One major difference is that slice indexing of a list copies the elements into a new list, but slicing
an array returns a view: an object that refers to the data in the original array. The original array
can be mutated using the view.
>>> b = a[3:]
>>> b
array([4, 5, 6])
>>> b[0] = 40
>>> a
array([ 10, 2, 3, 40, 5, 6])

2D arrays
Two- and higher-dimensional arrays can be initialized from nested Python sequences:
>>> a = [Link]([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
>>> a
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
In NumPy, a dimension of an array is sometimes referred to as an “axis”. This terminology may
be useful to disambiguate between the dimensionality of an array and the dimensionality of the
data represented by the array. For instance, the array ‘a’ could represent three points, each lying
within a four-dimensional space, but ‘a’ has only two “axes”.
Another difference between an array and a list of lists is that an element of the array can be
accessed by specifying the index along each axis within a single set of square brackets, separated
by commas. For instance, the element 8 is in row 1 and column 3:
>>>a[1, 3]
8
In list it is accessed as a[1][3]

Array attributes
The ndim, shape, size, and dtype are attributes of an array.
ndim– number of dimensions of the array
shape- The shape of an array is a tuple of non-negative integers that specify the number of
elements along each dimension or the size of each dimension.
size - total number of elements in array.
dtype – data type of the elements in array.
Examples:
>>>[Link]
2
>>>[Link]
(3, 4)
>>> len([Link]) == [Link]
True
>>>[Link]
12
>>>[Link]
dtype('int64')

Numpy array can be created using the following methods:


[Link](), [Link](), [Link](), [Link](), [Link]()

Create an array filled with 0’s:


>>> [Link](2)
array([0., 0.])

An array filled with 1’s:


>>> [Link](2)
array([1., 1.])

Or even an empty array! The function empty creates an array whose initial content is random and
depends on the state of the memory. The reason to use empty over zeros (or something similar) is
speed - just make sure to fill every element afterwards!
>>> # Create an empty array with 2 elements
>>> [Link](2)
array([3.14, 42. ]) # may vary
You can create an array with a range of elements:
>>> [Link](4)
array([0, 1, 2, 3])

And even an array that contains a range of evenly spaced intervals. To do this, you will specify
the first number, last number, and the step size.
>>> [Link](2, 9, 2)
array([2, 4, 6, 8])
You can also use [Link]() to create an array with values that are spaced linearly in a
specified interval:
>>> [Link](0, 10, num=5)
array([ 0. , 2.5, 5. , 7.5, 10. ])

Specifying your data type


While the default data type is floating point (np.float64), you can explicitly specify which data
type you want, using the dtype keyword.
x = [Link](2, dtype=np.int64)
>>> x
array([1, 1])
Basic Arithmetic Operations on NumPy Arrays
Basic mathematical functions perform element-wise operation on arrays and are available both as
operator overloads and as functions in the NumPy module.
[Link], [Link], [Link], [Link] (+,-,*,/)

For example,
1. >>> import numpy as np
2. >>> a = [Link]( [20, 30, 40, 50] )
3. >>> b = [Link](4)
4. >>> b
array([0, 1, 2, 3])
5. >>> a + b
array([20, 31, 42, 53])
6. >>> [Link](a, b)
array([20, 31, 42, 53])
7. >>> a – b
array([20, 29, 38, 47])
8. >>> [Link](a, b)
array([20, 29, 38, 47])
9. >>> A = [Link]( [[1, 1], [6, 1]] )
10. >>> B = [Link]( [[2, 8], [3, 4]] )
11. >>> A * B
array([[2, 8],
[18, 4]])
12. >>> [Link](A, B)
array([[ 2, 8],
[18, 4]])
13. >>> A / B
array([[0.5 , 0.125],
[2. , 0.25 ]])
14. >>> [Link](A, B)
array([[0.5 , 0.125],
[2. , 0.25 ]])
15. >>> [Link](A, B)
array([[ 5, 12],
[15, 52]])
16. >>> B**2
array([[ 4, 64],
[ 9, 16]], dtype=int32)

Mathematical Functions in NumPy


Various mathematical functions are supported in NumPy. A few frequently used mathematical
functions are shown below.
1. >>> import numpy as np
2. >>> a = [Link]( [20, 30, 40, 50] )
3. >>> [Link](a)
array([ 0.91294525, -0.98803162, 0.74511316, -0.26237485])
4. >>> [Link](a)
array([ 0.40808206, 0.15425145, -0.66693806, 0.96496603])
5. >>> [Link](a)
array([ 2.23716094, -6.4053312 , -1.11721493, -0.27190061])
6. >>> a = [Link]([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
7. >>> [Link](a)
array([-2., -2., -1., 0., 1., 1., 2.])
8. >>> [Link](a)
array([-1., -1., -0., 1., 2., 2., 2.])
9. >>> [Link]([1,4,9])
array([ 1., 2., 3.])
10. >>> [Link]([2, 3, 4], [1, 5, 2])
array([2, 5, 4])
11. >>> [Link]([2, 3, 4], [1, 5, 2])
array([1, 3, 2])
12. >>> [Link]([0.5, 1.5])
2.0
13. >>> [Link]([[0, 1], [0, 5]], axis=0)
array([0, 6])
14. >>> [Link]([[0, 1], [0, 5]], axis=1)
array([1, 5])

Changing the Shape of an Array


Method: [Link](array, new_shape)

The reshape() method in NumPy is used to change the shape of an array without modifying its
data. It creates a new view of the array with the specified shape, as long as the total number of
elements remains the same.

Syntax
[Link](array, new_shape)
# or as a method of ndarray:
[Link](new_shape)

Parameters
1. array: The array to be reshaped.
2. new_shape: A tuple or integer specifying the desired shape. One dimension can be -1,
which allows NumPy to infer the size automatically based on the total number of
elements.
Key Points
 The reshaped array shares the same data buffer as the original array whenever possible.
 The total number of elements in the original and reshaped arrays must match.
 Efficient memory usage as the reshaped array is typically a view, not a copy.
 Useful for data preprocessing and reshaping tensors in machine learning workflows.

Example:
import numpy as np
# Original array
arr = [Link]([1, 2, 3, 4, 5, 6])

# Reshape into 2x3


reshaped = [Link](2, 3)
print(reshaped)
# Output:
# [[1 2 3]
# [4 5 6]]

# Reshape with one dimension inferred


reshaped_auto = [Link](-1, 3)
print(reshaped_auto)
# Output:
# [[1 2 3]
# [4 5 6]]

Stacking and Splitting of Arrays


—->[Link](): Horizontal Split in NumPy
The [Link]() function is used to split an array into multiple sub-arrays horizontally
(along its columns). It is particularly useful for dividing a 2D array or higher-dimensional arrays
into equal parts.

syntax:
[Link](array, indices_or_sections)
Parameters
1. array: The input array to be split.
2. indices_or_sections:
o An integer, specifying the number of equal-sized parts to split the array into.
o A 1D array of indices specifying where the splits should occur.
It returns A list of sub-arrays split from the input array.
Key Points
 The function splits along the second axis (axis=1) for 2D arrays.
 For higher dimensions, it splits along the axis corresponding to columns.
 If the array can't be split evenly, it raises a ValueError.
[Link]() function
The [Link]() function is used to split an array into multiple sub-arrays vertically (row-
wise). vsplit() is equivalent to split with axis=0 (default), the array is always split along the first
axis regardless of the array dimension.
The [Link]() function is useful when dealing with large datasets that need to be processed
in parallel. By dividing the dataset into smaller chunks, multiple processors can work on
different parts of the dataset at the same time, thus reducing processing time
[Link](ary, indices_or_sections)

You can stack several arrays together or split an array to several arrays. For example,
1. >>> import numpy as np
2. >>> a = [Link]([[3, 1], [8, 7]])
3. >>> b = [Link]([[2, 4], [4, 8]])
4. >>> [Link]((a, b))
array([[3, 1],
[8, 7],
[2, 4],
[4, 8]])
5. >>> [Link]((a, b))
array([[3, 1, 2, 4],
[8, 7, 4, 8]])
6. >>> a = [Link](10*[Link]((2, 12)))
7. >>> a
array([[8., 3., 6., 3., 5., 5., 5., 8., 9., 7., 6., 8.],
[8., 3., 1., 2., 9., 0., 5., 5., 0., 3., 3., 8.]])
8. >>> [Link](a, 3)
[array([[8., 3., 6., 3.],
[8., 3., 1., 2.]]), array([[5., 5., 5., 8.],
[9., 0., 5., 5.]]), array([[9., 7., 6., 8.],
[0., 3., 3., 8.]])]
9. >>> [Link](a, (3, 4))
[array([[8., 3., 6.],
[8., 3., 1.]]), array([[3.],
[2.]]), array([[5., 5., 5., 8., 9., 7., 6., 8.],
[9., 0., 5., 5., 0., 3., 3., 8.]])]
10. >>> [Link](a, 2)
[array([[2., 9., 4., 4., 3., 0., 2., 9., 1., 2., 0., 1.]]),
array([[3., 4., 8., 2., 5., 8., 5., 5., 7., 7.,7., 8.]])]

[Link]() function:
The [Link]() function is used to stack arrays in sequence horizontally (column wise).
This is equivalent to concatenation along the second axis, except for 1-D arrays where it
concatenates along the first axis. Rebuilds arrays divided by hsplit.
This function is useful in the scenarios when we have to concatenate two arrays of different
shapes along the second axis (column-wise). For example, to combine two arrays of shape (n, m)
and (n, l) to form an array of shape (n, m+l).

Syntax:
[Link](arr)
[Link]() function

[Link]() function is used to stack arrays vertically (row-wise) to make a single array. It
takes a sequence of arrays and joins them vertically. This is equivalent to concatenation along the
first axis after 1-D arrays of shape (N,) have been reshaped to (1,N).
This function is useful when you have two or more arrays with the same number of columns, and
you want to concatenate them vertically (row-wise). It is also useful to append a single array as a
new row to an existing 2D array.
Syntax:
[Link](arr)

Broadcasting
The term broadcasting describes how NumPy treats arrays with different shapes during
arithmetic operations. Broadcasting allows NumPy functions to deal in a meaningful way with
input arrays that do not have exactly the same shape. Subject to certain constraints, the smaller
array is “broadcast” across the larger array so that they have compatible shapes and occurs
automatically whenever possible. The rules of broadcasting are:
• Rule 1 → If two input arrays do not have the same number of dimensions, a “1” will repeatedly
be padded to the shape of the smaller array on its left side by NumPy so both the arrays have the
same number of dimensions.
• Rule 2 → If the shape of two input arrays does not match, then the array with a shape of “1”
along a particular dimension is stretched by NumPy to match the shape of the array having the
largest shape along that dimension. The value of the array element is assumed to be the same
along that dimension for the “broadcast” array. After application of the broadcasting rules, the
sizes of all arrays must match.
• Rule 3 → If the above two rules are not met, a ValueError: frames are not aligned exception is
thrown, indicating that the arrays have incompatible shapes.

Example-1.
1. >>> import numpy as np
2. >>> array_1 = [Link]([4, 5])
3. >>> array_2 = [Link](5)
4. >>> array_1 + array_2
array([[0.20188425, 1.20188425, 2.20188425, 3.20188425],
[0.51342227, 1.51342227, 2.51342227, 3.51342227],
[0.03364189, 1.03364189, 2.03364189, 3.03364189],
[0.6176858 , 1.6176858 , 2.6176858 , 3.6176858 ]])

How broadcasting is applied to do this addition:


array_1.shape → (4, 5)
array_2.shape → (5,)
Since array_2 has less dimension compared to array_1, according to Rule 1, array_2 is padded
with 1’s on its left. Now the shape of array_2 becomes (1, 5). NumPy automatically handles this
step.
array_1.shape (4, 5)
array_2.shape (1, 5)
Next, according to Rule 2, the shape of array_2 having “1” in the first dimension is stretched to
match the highest shape along that dimension of array_1. The shape of array_2 becomes (4, 5).
NumPy automatically handles this step.
array_1.shape → (4, 5)
array_2.shape → (4, 5)
After stretching, the elements of array_2 seems to be stacked upon themselves for four times
along the first dimension. The elements of array_2 appear to be the copies of the original array.
array_2 → array([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]])
Example-2:
1. >>> import numpy as np
2. >>> array_1 = [Link]([2, 3])
3. >>> array_2 = [Link](5)
4. >>> array_1.shape
(2, 3)

5. >>> array_2.shape
(5,)
6. >>> array_1 + array_2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (2,3) (5,)
array_1.shape → (2, 3)
array_2.shape → (5,)
Since array_2 has less dimension compared to array_1, according to Rule 1, array_2 is padded
with 1’s on its left. Now the shape of array_2 becomes (1, 5).
array_1.shape → (2, 3)
array_2.shape → (1, 5)
Next, according to Rule 2, the shape of array_2 having “1” in the first dimension is stretched to
match the highest shape along that dimension of array_1. Thus, the shape of
array_2 becomes (2, 5).
array_1.shape → (2, 3)
array_2.shape → (2, 5)
But the shapes of both the arrays differ and according to Rule 3 the addition operation fails in
this case.

You might also like