0% found this document useful (0 votes)
32 views18 pages

Num Py

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)
32 views18 pages

Num Py

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
You are on page 1/ 18

Basics of NumPy Arrays

NumPy stands for Numerical Python. It is a Python library used for


working with an array. In Python, we use the list for the array but it’s slow
to process. NumPy array is a powerful N-dimensional array object and is
used in linear algebra, Fourier transform, and random number capabilities.
It provides an array object much faster than traditional Python lists.
Types of Array:
1. One Dimensional Array
2. Multi-Dimensional Array

One Dimensional Array:


A one-dimensional array is a type of linear array.

One Dimensional Array

Example:

# importing numpy module


import numpy as np

# creating list
list = [1, 2, 3, 4]

# creating numpy array


sample_array = np.array(list)

print("List in python : ", list)


print("Numpy Array in python :", sample_array)
List in python : [1, 2, 3, 4]
Numpy Array in python : [1 2 3 4]
1
Check data type for list and array:
print(type(list_1))

print(type(sample_array))

<class 'list'>
<class 'numpy.ndarray'>

Multi-Dimensional Array:
Data in multidimensional arrays are stored in tabular form.

Two Dimensional Array

# importing numpy module


import numpy as np

# creating list
list_1 = [1, 2, 3, 4]
list_2 = [5, 6, 7, 8]
list_3 = [9, 10, 11, 12]

# creating numpy array


sample_array = np.array([list_1, list_2, list_3])

print("Numpy multi dimensional array in python\n",


sample_array)

Output
Numpy multi dimensional array in python
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]

NumPy Creating Arrays


2
NumPy is used to work with arrays. The array object in
NumPy is called ndarray.

We can create a NumPy ndarray object by using


the array() function.

import numpy as np

arr = np.array([1, 2, 3, 4, 5])


print(arr)
print(type(arr))

[1 2 3 4 5]
<class 'numpy.ndarray'>

To create an ndarray, we can pass a list, tuple or any array-


like object into the array() method, and it will be converted
into an ndarray:

Example

Use a tuple to create a NumPy array:


import numpy as np
arr = np.array((1, 2, 3, 4, 5))
print(arr)

[1 2 3 4 5]

Dimensions in Arrays
A dimension in arrays is one level of array depth (nested
arrays).

3
nested array: are arrays that have arrays as their elements.

0-D Arrays
0-D arrays, or Scalars, are the elements in an array.
Each value in an array is a 0-D array.

Example
Create a 0-D array with value 42.
import numpy as np
arr = np.array(42)
print(arr)

1-D Arrays
An array that has 0-D arrays as its elements is called uni-
dimensional or 1-D array.

These are the most common and basic arrays.

Example
Create a 1-D array containing the values 1,2,3,4,5:

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
[1 2 3 4 5]

4
2-D Arrays
An array that has 1-D arrays as its elements is called a
2-D array.

These are often used to represent matrix or 2nd order


tensors.

NumPy has a whole sub module dedicated towards


matrix operations called numpy.mat

Example

Create a 2-D array containing two arrays with the values


1,2,3 and 4,5,6:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
[[1 2 3]
[4 5 6]]

3-D arrays
An array that has 2-D arrays (matrices) as its elements is called 3-D
array.

These are often used to represent a 3rd order tensor.

Example
Create a 3-D array with two 2-D arrays, both containing two
arrays with the values 1,2,3 and 4,5,6:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]],

5
[[1, 2, 3], [4, 5, 6]]])
print(arr)
[[[1 2 3]
[4 5 6]]

[[1 2 3]
[4 5 6]]]

Check Number of Dimensions?


NumPy Arrays provides the ndim attribute that returns an
integer that tells us how many dimensions the array
have.

Example
Check how many dimensions the arrays have:

import numpy as np
a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3],
[4, 5, 6]]])
print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)
0
1
2
3

6
Higher Dimensional Arrays
An array can have any number of dimensions.

When the array is created, you can define the number of


dimensions by using the ndmin argument.

Example
Create an array with 5 dimensions and verify that it has 5
dimensions:

import numpy as np
arr = np.array([1, 2, 3, 4], ndmin=5)
print(arr)
print('number of dimensions :', arr.ndim)

[[[[[1 2 3 4]]]]]
number of dimensions : 5

NumPy Array Indexing


Access Array Elements
Array indexing is the same as accessing an array element.

You can access an array element by referring to its index


number.

The indexes in NumPy arrays start with 0, meaning that the


first element has index 0, and the second has index 1 etc.

Example
Get the first element from the following array:

7
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[0])
1

Example
Get the second element from the following array.
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[1])

Example
Get third and fourth elements from the following array and
add them.

import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[2] + arr[3])

Access 2-D Arrays


To access elements from 2-D arrays we can use comma
separated integers representing the dimension and the
index of the element.

Think of 2-D arrays like a table with rows and columns,


where the dimension represents the row and the index
represents the column.

8
Example
Access the element on the first row, second column:

import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('2nd element on 1st row: ', arr[0, 1])
2nd element on 1st dim: 2

Example

Access the element on the 2nd row, 5th column:


import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('5th element on 2nd row: ', arr[1, 4])
5th element on 2nd dim: 10

Access 3-D Arrays


To access elements from 3-D arrays we can use comma
separated integers representing the dimensions and the
index of the element.

Example
Access the third element of the second array of the first array:

import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9],
[10, 11, 12]]])
print(arr[0, 1, 2])

9
Example Explained

arr[0, 1, 2] prints the value 6.

And this is why:

The first number represents the first dimension,


which contains two arrays:
[[1, 2, 3], [4, 5, 6]]
and:
[[7, 8, 9], [10, 11, 12]]
Since we selected 0, we are left with the first array:
[[1, 2, 3], [4, 5, 6]]

The second number represents the second dimension,


which also contains two arrays:
[1, 2, 3]
and:
[4, 5, 6]
Since we selected 1, we are left with the second
array:
[4, 5, 6]

The third number represents the third dimension,


which contains three values:
4
5
6
Since we selected 2, we end up with the third value:
6

Negative Indexing
Use negative indexing to access an array from the end.

10
Example
Print the last element from the 2nd dim:

import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('Last element from 2nd dim: ', arr[1, -1])
Last element from 2nd dim: 10

NumPy Array Slicing


Slicing arrays
Slicing in python means taking elements from one given
index to another given index.

We pass slice instead of index like this: [start:end].

We can also define the step, like this: [start:end:step].

If we don't pass start its considered 0

If we don't pass end its considered length of array in that


dimension

If we don't pass step its considered 1

Example
Slice elements from index 1 to index 5 from the following array:

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

11
Example

Slice elements from index 4 to the end of the array:

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

Example
Slice elements from the beginning to index 4 (not included):

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

Negative Slicing
Use the minus operator to refer to an index from the end:

Example
Slice from the index 3 from the end to index 1 from the end:

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

STEP
Use the step value to determine the step of the slicing:

12
Example
Return every other element from index 1 to index 5:

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

Example
Return every other element from the entire array:

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

Slicing 2-D Arrays


Example
From the second element, slice elements from index 1 to
index 4 (not included):

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

Example
From both elements, return index 2:

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

13
print(arr[0:2, 2])
[3 8]

Example
From both elements, slice index 1 to index 4 (not included),
this will return a 2-D array:

import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0:2, 1:4])
[[2 3 4]
[7 8 9]]

numpy.swapaxes() function | Python


numpy.swapaxes() function interchange two axes of an array.
Syntax : numpy.swapaxes(arr, axis1, axis2)
Parameters :
arr : [array_like] input array.
axis1 : [int] First axis.
axis2 : [int] Second axis.

Return : [ndarray] In earlier NumPy versions, a view of arr is returned


only if the order of the axes is changed, otherwise the input array is
returned. For NumPy >= 1.10.0, if arr is an ndarray, then a view of arr is
returned; otherwise a new array is created.

# Python program explaining


# numpy.swapaxes() function

# importing numpy as np
import numpy as np

14
arr = np.array([[2, 4, 6]])
gfg = np.swapaxes(arr, 0, 1)
print (gfg)
Output :
[[2]
[4]
[6]]

Code #2 :
# Python program explaining
# numpy.swapaxes() function

# importing numpy as np
import numpy as np
arr = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]])
gfg = np.swapaxes(arr, 0, 2)
print (gfg)

Output :
[[[0 4]
[2 6]]
[[1 5]
[3 7]]]

Python | Numpy numpy.transpose()


With the help of Numpy numpy.transpose(), We can perform the simple
function of transpose within one line by using numpy.transpose() method
of Numpy. It can transpose the 2-D arrays on the other hand it has no
effect on 1-D arrays. This method transpose the 2-D numpy array.

Parameters:
axes : [None, tuple of ints, or n ints] If anyone wants to pass the
parameter then you can but it’s not all required. But if you want than
remember only pass (0, 1) or (1, 0). Like we have array of shape (2, 3) to
change it (3, 2) you should pass (1, 0) where 1 as 3 and 0 as 2.
Returns: ndarray

15
Example #1 :
In this example we can see that it’s really easy to transpose an array with
just one line.

# importing python module named numpy


import numpy as np

# making a 3x3 array


gfg = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

# before transpose
print(gfg, end ='\n\n')

# after transpose
print(gfg.transpose())

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

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

16
Example #2 :
In this example we demonstrate the use of tuples in numpy.transpose().

# importing python module named numpy


import numpy as np

# making a 3x3 array


gfg = np.array([[1, 2],[4, 5],[7, 8]])

# before transpose
print(gfg, end ='\n\n')

# after transpose
print(gfg.transpose(1, 0))
Output:
[[1 2]
[4 5]
[7 8]]

[[1 4 7]
[2 5 8]]

Method 2: Using Numpy ndarray.T object.


# importing python module named numpy
import numpy as np

# making a 3x3 array


gfg = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
17
# before transpose
print(gfg, end ='\n\n')

# after transpose
print(gfg.T)
Output
[[1 2 3]
[4 5 6]
[7 8 9]]

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

18

You might also like