0% found this document useful (0 votes)
14 views29 pages

Nmpy - 1 - Data Science

This document discusses different ways to create arrays in NumPy. It shows how to create 1D, 2D and multidimensional arrays using functions like array, zeros, ones, linspace, and full. It also demonstrates getting array properties like shape, size and dtype.
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)
14 views29 pages

Nmpy - 1 - Data Science

This document discusses different ways to create arrays in NumPy. It shows how to create 1D, 2D and multidimensional arrays using functions like array, zeros, ones, linspace, and full. It also demonstrates getting array properties like shape, size and dtype.
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/ 29

5/28/24, 12:38 AM Nmpy_1

...................................................................................................................................................................................................

Srikanta Gouda

Numpy Practice Sheet

How to create Array


1> By using Array module

2> By using numpy module

Interviw Question? Array concrpt is there in python or not ?

Not avalable but we can create from external libraries one is by usion "Array module" and
another is using "Numpy module or library ."

In [8]: # By using array module


import array
a= array.array('i',[10,20,30])
print(a)

for x in a:
print(x)

# Note: not recomondate to use cz much libraries are not support.

array('i', [10, 20, 30])


10
20
30

In [12]: # By using numpy module

import numpy as np
a= np.array([10,20,30,40])
print(a)
print(type(a))

print('Element one by one')


for x in a:
print(x)

[10 20 30 40]
<class 'numpy.ndarray'>
Element one by one
10
20
30
40

How to create Numpy Arrays :

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 1/29
5/28/24, 12:38 AM Nmpy_1

In [16]: # Create 1-D Array


import numpy as np
a= np.array([10,20,30])
type(a)
print(a)
a.ndim

[10 20 30]
1
Out[16]:

In [20]: # Create 2-D Array


import numpy as np
a= np.array([[10,20,30,40],[10,20,30,40],[10,20,30,40]])
type(a)
a.ndim
print(a)

[[10 20 30 40]
[10 20 30 40]
[10 20 30 40]]

In [11]: # Create 1-D Array From the Tuple

import numpy as np
a= np.array(('Siku','Biku','Chiku'))
print(type(a))
print(a)
print(a.ndim)
print(a.shape)

<class 'numpy.ndarray'>
['Siku' 'Biku' 'Chiku']
1
(3,)

In [15]: # Creating array by using "dtype=object".

import numpy as np
a= np.array([10,'Siku',10.5,True,10+20j],dtype=object)
a
# type(a)

array([10, 'Siku', 10.5, True, (10+20j)], dtype=object)


Out[15]:

In [5]: # arrange()

import numpy as np
a = np.arange(0,10)
a

array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Out[5]:

In [6]: import numpy as np


a = np.arange(1,11)
a

array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Out[6]:

In [ ]: import numpy as np
a = np.arange(1,11,2)
a

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 2/29
5/28/24, 12:38 AM Nmpy_1

In [9]: import numpy as np


a = np.arange(1,11,3,dtype=float)
a

array([ 1., 4., 7., 10.])


Out[9]:

In [12]: # Only stop value ==> 0 to stop-1

import numpy as np
a= np.arange(10)
print(""a.ndim)
#print(f'a={a}')
#print(f'The dimension of the array is: ,{a.ndim}' )

In [16]: # linspace():

import numpy as np
a= np.linspace(0,1)
print(a)
print(a.shape)
print(a.ndim)

[0. 0.02040816 0.04081633 0.06122449 0.08163265 0.10204082


0.12244898 0.14285714 0.16326531 0.18367347 0.20408163 0.2244898
0.24489796 0.26530612 0.28571429 0.30612245 0.32653061 0.34693878
0.36734694 0.3877551 0.40816327 0.42857143 0.44897959 0.46938776
0.48979592 0.51020408 0.53061224 0.55102041 0.57142857 0.59183673
0.6122449 0.63265306 0.65306122 0.67346939 0.69387755 0.71428571
0.73469388 0.75510204 0.7755102 0.79591837 0.81632653 0.83673469
0.85714286 0.87755102 0.89795918 0.91836735 0.93877551 0.95918367
0.97959184 1. ]
(50,)
1

In [18]: import numpy as np


a=np.linspace(1,100,6,dtype=int)
a

array([ 1, 20, 40, 60, 80, 100])


Out[18]:

In [14]: # zeros()

import numpy as np
a= np.zeros((3,3,4)) #by default type is "float type"
print(a)

[[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]

[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]

[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]]

In [13]: import numpy as np


b= np.zeros((2,3,4), dtype=int)
print(b)

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 3/29
5/28/24, 12:38 AM Nmpy_1
[[[0 0 0 0]
[0 0 0 0]
[0 0 0 0]]

[[0 0 0 0]
[0 0 0 0]
[0 0 0 0]]]

In [4]: import numpy as np


a= np. zeros((2,2,3,4))

array([[[[0., 0., 0., 0.],


Out[4]:
[0., 0., 0., 0.],
[0., 0., 0., 0.]],

[[0., 0., 0., 0.],


[0., 0., 0., 0.],
[0., 0., 0., 0.]]],

[[[0., 0., 0., 0.],


[0., 0., 0., 0.],
[0., 0., 0., 0.]],

[[0., 0., 0., 0.],


[0., 0., 0., 0.],
[0., 0., 0., 0.]]]])

In [22]: # finding total size

import numpy as np
a= np.zeros((2,3,4))
print(a)
print(a.size)

[[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]

[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]]
24

In [17]: import numpy as np


a = np.ones(10)
a

array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
Out[17]:

In [3]: import numpy as np


a= np.ones((2,3,4),dtype=int)
a

array([[[1, 1, 1, 1],
Out[3]:
[1, 1, 1, 1],
[1, 1, 1, 1]],

[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]]])

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 4/29
5/28/24, 12:38 AM Nmpy_1

In [23]: import numpy as np


a=help(np.full)
a

Help on function full in module numpy:

full(shape, fill_value, dtype=None, order='C', *, like=None)


Return a new array of given shape and type, filled with `fill_value`.

Parameters
----------
shape : int or sequence of ints
Shape of the new array, e.g., ``(2, 3)`` or ``2``.
fill_value : scalar or array_like
Fill value.
dtype : data-type, optional
The desired data-type for the array The default, None, means
``np.array(fill_value).dtype``.
order : {'C', 'F'}, optional
Whether to store multidimensional data in C- or Fortran-contiguous
(row- or column-wise) order in memory.
like : array_like, optional
Reference object to allow the creation of arrays which are not
NumPy arrays. If an array-like passed in as ``like`` supports
the ``__array_function__`` protocol, the result will be defined
by it. In this case, it ensures the creation of an array object
compatible with that passed in via this argument.

.. versionadded:: 1.20.0

Returns
-------
out : ndarray
Array of `fill_value` with the given shape, dtype, and order.

See Also
--------
full_like : Return a new array with shape of input filled with value.
empty : Return a new uninitialized array.
ones : Return a new array setting values to one.
zeros : Return a new array setting values to zero.

Examples
--------
>>> np.full((2, 2), np.inf)
array([[inf, inf],
[inf, inf]])
>>> np.full((2, 2), 10)
array([[10, 10],
[10, 10]])

>>> np.full((2, 2), [1, 2])


array([[1, 2],
[1, 2]])

In [31]: import numpy as np


a=np.full((3,4),5,dtype=float)
a

array([[5., 5., 5., 5.],


Out[31]:
[5., 5., 5., 5.],
[5., 5., 5., 5.]])

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 5/29
5/28/24, 12:38 AM Nmpy_1

In [38]: import numpy as np


a=np.full((2,3,4),7,dtype=float)
a

array([[[7., 7., 7., 7.],


Out[38]:
[7., 7., 7., 7.],
[7., 7., 7., 7.]],

[[7., 7., 7., 7.],


[7., 7., 7., 7.],
[7., 7., 7., 7.]]])

Function **
In [14]: def f1(a,*,b):
print(f'The value of a: {a}')
print(f'The value of b: {b}')
#f1(10,20)
#f1(a=10,b=20)
f1(10,b=20)
#f1(10,b=20)

The value of a: 10
The value of b: 20

In [5]: # random Module


# random.randint()
import numpy as np
a= np.random.randint(10,20)
a

13
Out[5]:

In [8]: # Create 1-D Array

import numpy as np
np.random.randint(1,9,size=10)

array([5, 2, 7, 5, 6, 2, 5, 2, 3, 7])
Out[8]:

In [9]: # Generate Random no.


import numpy as np
np.random.randint(10,size=9)

array([0, 6, 7, 6, 5, 7, 3, 4, 2])
Out[9]:

In [13]: import numpy as np


np.random.randint(100,size=(3,4))

array([[90, 44, 11, 71],


Out[13]:
[38, 64, 79, 69],
[73, 11, 89, 99]])

In [14]: import numpy as np


np.random.randint(100,size=(2,3,4))

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 6/29
5/28/24, 12:38 AM Nmpy_1
array([[[50, 70, 70, 93],
Out[14]:
[88, 70, 73, 82],
[53, 61, 52, 35]],

[[39, 25, 92, 1],


[92, 47, 21, 40],
[69, 16, 44, 13]]])

In [10]: import numpy as np


a= np.random.randint(1,11,size=(20,30))
a.dtype

dtype('int32')
Out[10]:

In [21]: # check memory utilization

import numpy as np
import sys
a= np.random.randint(1,100, size=(2,3))
print(f'size of the array: {sys.getsizeof(a)}')
b= np.random.randint(1,100, size=(2,3),dtype= 'int8')
print(f"The size of the int-8 size: {sys.getsizeof(b)}")
c= np.random.randint(1,100, size=(2,3),dtype= 'int16')
print(f"The size of the int-8 size: {sys.getsizeof(c)}")
d= np.random.randint(1,100, size=(2,3),dtype= 'int64')
print(f"The size of the int-8 size: {sys.getsizeof(d)}")

size of the array: 152


The size of the int-8 size: 134
The size of the int-8 size: 140
The size of the int-8 size: 176

In [25]: # rand()
# generate rando value using rand function

import numpy as np
a= np.random.rand()
a

0.27904189827849124
Out[25]:

In [26]: # 1-D Array with flot values from 0 to 1


# Generate a 10 values from the range of 0 to 1

import numpy as np
a= np.random.rand(10)
a

array([0.72792139, 0.94743558, 0.6011281 , 0.63303088, 0.6684518 ,


Out[26]:
0.12549857, 0.58416029, 0.73327667, 0.32673649, 0.05656741])

In [29]: # 2-D Array with float values from 0 to 1

import numpy as np
a= np.random.rand(3,3)
a

array([[0.1556086 , 0.37041247, 0.26835923],


Out[29]:
[0.82838652, 0.05413248, 0.08343486],
[0.18959555, 0.50648854, 0.59090751]])

In [31]: # 3-D Array with the float values from 0 to 1

import numpy as np

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 7/29
5/28/24, 12:38 AM Nmpy_1
a= np.random.rand(2,3,3)
a

array([[[0.30241417, 0.29130541, 0.15518769],


Out[31]:
[0.85682369, 0.00333481, 0.15528877],
[0.93720159, 0.39376314, 0.98066036]],

[[0.96270742, 0.44606529, 0.74641823],


[0.98841704, 0.08446494, 0.0371119 ],
[0.98912599, 0.36229887, 0.44056159]]])

In [38]: # unform()
# create random array with custmize value

import numpy as np
np.random.uniform()

# a= np.random.uniform()
#a

0.6641641512998665
Out[38]:

In [41]: # Create 1-D Array with customize values

import numpy as np
a= np.random.uniform(10,20,size=(3))
a

array([11.08014875, 12.46241474, 16.20518873])


Out[41]:

In [43]: # Create 2-D Array wih CVustomize values

import numpy as np
a= np.random.uniform(1,100,size=(3,3))
a

array([[59.43680357, 18.52641422, 43.17714851],


Out[43]:
[88.83592129, 18.87499441, 49.78698311],
[28.88199872, 92.86349393, 46.27560882]])

In [44]: # Create 3-D array with customize values

import numpy as np
a= np.random.uniform(1,100,size=(3,3,4))
a

array([[[26.65397829, 83.44808376, 45.2159112 , 17.15858839],


Out[44]:
[24.62865621, 61.29673138, 11.68144221, 6.85830435],
[23.37395951, 62.10513244, 30.26879659, 5.39127431]],

[[ 7.35251954, 46.06795939, 65.90330119, 79.99473662],


[79.97188813, 5.28070941, 77.62308299, 2.95815893],
[63.4441971 , 5.86159283, 9.42531224, 2.99626376]],

[[57.40363695, 40.50976219, 12.03472668, 62.5592618 ],


[23.84422911, 47.62595181, 65.11708538, 37.35058441],
[21.87891802, 43.00170368, 69.48370141, 74.57242506]]])

visualizion library Matplotlib


In [51]: # Visualize the unform distibution by using Matplotlib
import numpy as np
s= np.random.uniform(10,20,size=(1000000))

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 8/29
5/28/24, 12:38 AM Nmpy_1
import matplotlib.pyplot as plt
count, bins, ignored = plt.hist(s, 15, density=True)
plt.plot(bins,np.ones_like(bins), linewidth=2, color='r')
plt.show()

In [24]: import numpy as np


a= np.random.rand(4,3,3)
a

array([[[0.619984 , 0.20734772, 0.88273494],


Out[24]:
[0.48599373, 0.9517234 , 0.24192536],
[0.18232509, 0.26727453, 0.99229383]],

[[0.28908356, 0.95337739, 0.79135328],


[0.95050217, 0.76748028, 0.01172654],
[0.61288776, 0.11835073, 0.17607175]],

[[0.30119237, 0.75957418, 0.4527601 ],


[0.62637883, 0.99039502, 0.27215047],
[0.82170369, 0.91979375, 0.97992868]],

[[0.11477135, 0.94422246, 0.53002313],


[0.22426052, 0.10315539, 0.48310927],
[0.97581946, 0.29474829, 0.80952909]]])

In [25]: import numpy as np


np.random.randn(3,4)

array([[ 1.31023897, 1.07884663, -0.88244024, 0.59132099],


Out[25]:
[-1.2393973 , 0.9362874 , -1.39483468, 1.30549389],
[ 0.00433769, -0.86189701, -2.0415996 , 1.31609342]])

In [26]: # Suffle()
# 1-D Array
import numpy as np
a= np.arange(9)
a

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 9/29
5/28/24, 12:38 AM Nmpy_1
np.random.shuffle(a)
print(a)

[3 0 4 5 2 6 1 7 8]

In [36]: #2-D Array

import numpy as np

a= np.random.randint(1,100,size=(6,5))
print("Before Shuffle")
print(a)
np.random.shuffle(a)
print("After Shuffle")
print(a)

Before Shuffle
[[ 2 39 25 28 99]
[79 84 14 60 36]
[35 98 46 45 16]
[15 59 8 40 84]
[76 47 21 20 14]
[24 15 91 46 53]]
After Shuffle
[[ 2 39 25 28 99]
[24 15 91 46 53]
[79 84 14 60 36]
[35 98 46 45 16]
[76 47 21 20 14]
[15 59 8 40 84]]

In [55]: # 3-D Array

import numpy as np
a= np.arange(48).reshape(4,3,4)
np.random.shuffle(a)
print(a)

[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]

[[36 37 38 39]
[40 41 42 43]
[44 45 46 47]]

[[24 25 26 27]
[28 29 30 31]
[32 33 34 35]]

[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]

In [ ]: array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],

[[12, 13, 14, 15],


[16, 17, 18, 19],
[20, 21, 22, 23]],

[[24, 25, 26, 27],


[28, 29, 30, 31],
[32, 33, 34, 35]],

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 10/29
5/28/24, 12:38 AM Nmpy_1

[[36, 37, 38, 39],


[40, 41, 42, 43],
[44, 45, 46, 47]]])

Array Attributes and Numpy Data Types

In [61]: # 1-D Array


import numpy as np
a= np.array([10,20,30,40,50])
a
print(f"The Dimention of Given Aray is: {a.ndim}")
print(f"The Size of Given Aray is: {a.size}")
print(f"The Shape of Given Aray is: {a.shape}")
print(f"The Type of Given Aray is: {a.dtype}")
print(f"The ItemSize of Given Aray is: {a.itemsize}")

The Dimention of Given Aray is: 1


The Size of Given Aray is: 5
The Shape of Given Aray is: (5,)
The Type of Given Aray is: int32
The ItemSize of Given Aray is: 4

Error message for Array efined


In [70]: # 2-D Array
import numpy as np
a= np.array([[10,20,30,40,50,60],[30,50,60,40,30],[30,82,91,36]])
a
print(f"The Dimention of Given Aray is: {a.ndim}")
print(f"The Size of Given Aray is: {a.size}")
print(f"The Shape of Given Aray is: {a.shape}")
print(f"The Type of Given Aray is: {a.dtype}")
print(f"The ItemSize of Given Aray is: {a.itemsize}")

The Dimention of Given Aray is: 1


The Size of Given Aray is: 3
The Shape of Given Aray is: (3,)
The Type of Given Aray is: object
The ItemSize of Given Aray is: 8
C:\Users\Lenovo\AppData\Local\Temp\ipykernel_13032\149047080.py:3: VisibleDeprecat
ionWarning: Creating an ndarray from ragged nested sequences (which is a list-or-t
uple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecate
d. If you meant to do this, you must specify 'dtype=object' when creating the ndar
ray.
a= np.array([[10,20,30,40,50,60],[30,50,60,40,30],[30,82,91,36]])

In [74]: import numpy as np


a= np.array([[10,20,30],[30,20,40],[50,60,70]])
print(a)
print(f"The Dimention of Given Aray is: {a.ndim}")
print(f"The Size of Given Aray is: {a.size}")
print(f"The Shape of Given Aray is: {a.shape}")
print(f"The Type of Given Aray is: {a.dtype}")
print(f"The ItemSize of Given Aray is: {a.itemsize}")

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 11/29
5/28/24, 12:38 AM Nmpy_1
[[10 20 30]
[30 20 40]
[50 60 70]]
The Dimention of Given Aray is: 2
The Size of Given Aray is: 9
The Shape of Given Aray is: (3, 3)
The Type of Given Aray is: int32
The ItemSize of Given Aray is: 4

Indexing, Slicing And Advance Indexing


In [17]: # Accsing array element 2-D Array

import numpy as np
a= np.array([[10,20,30],[40,50,60]])
print(a)
print()
print(a[0][2]) #accesing 30
print(a[1][1]) #accessing 50

[[10 20 30]
[40 50 60]]

30
50

In [26]: # accessing 3-D Array

import numpy as np
a=[[[1,2,3],[4,5,6],[7,8,9]],[[10,11,12],[13,14,15],[16,17,18]]]
n= np.array(a)
print(n)
print(f"The shape of the array is: {n.shape}")
print(n[0][0][2])
print(n[1][2][1])
print(n[-1][-3][-3])

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

[[10 11 12]
[13 14 15]
[16 17 18]]]
The shape of the array is: (2, 3, 3)
3
17
10

In [48]: import numpy as np


a= np.arange(1,19).reshape(2,3,3)
print(a)
print('\nFor this index [-1][-3][-3] The value is: ',n[-1][-3][-3])

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

[[10 11 12]
[13 14 15]
[16 17 18]]]

For this index [-1][-3][-3] The value is: 10

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 12/29
5/28/24, 12:38 AM Nmpy_1

In [54]: # Element accessing in 4-D Array


# 1

import numpy as np
a= np.arange(1,37).reshape(2,2,3,3)
a

array([[[[ 1, 2, 3],
Out[54]:
[ 4, 5, 6],
[ 7, 8, 9]],

[[10, 11, 12],


[13, 14, 15],
[16, 17, 18]]],

[[[19, 20, 21],


[22, 23, 24],
[25, 26, 27]],

[[28, 29, 30],


[31, 32, 33],
[34, 35, 36]]]])

In [62]: # 2

import numpy as np
a= np.arange(1,121).reshape(2,3,4,5)
print(a)
print("\nThe Request value [1][1][1][2] is: ",a[1][1][1][2])
print("The Position of 88: ",np.where(a==88))

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 13/29
5/28/24, 12:38 AM Nmpy_1
[[[[ 1 2 3 4 5]
[ 6 7 8 9 10]
[ 11 12 13 14 15]
[ 16 17 18 19 20]]

[[ 21 22 23 24 25]
[ 26 27 28 29 30]
[ 31 32 33 34 35]
[ 36 37 38 39 40]]

[[ 41 42 43 44 45]
[ 46 47 48 49 50]
[ 51 52 53 54 55]
[ 56 57 58 59 60]]]

[[[ 61 62 63 64 65]
[ 66 67 68 69 70]
[ 71 72 73 74 75]
[ 76 77 78 79 80]]

[[ 81 82 83 84 85]
[ 86 87 88 89 90]
[ 91 92 93 94 95]
[ 96 97 98 99 100]]

[[101 102 103 104 105]


[106 107 108 109 110]
[111 112 113 114 115]
[116 117 118 119 120]]]]

The Request value [1][1][1][2] is: 88


The Position of 88: (array([1], dtype=int64), array([1], dtype=int64), array([1],
dtype=int64), array([2], dtype=int64))

In [13]: # Slice Operator


a=[10,20,30,40,50,60,70,80,90,100]
print(a)
print(a[:0])
print(a[5:-8])

[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
[]
[]

In [9]: import numpy as np

# Create a sample array


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

# Slice the array backwards with end as -1


result = arr[3:-1:-1]

print(result) # Output: []

[]

In [21]: import numpy as np


a= np.array([[10,20],[30,40],[50,60]])
print(a)
print(a[1][1]) #Applying indexing method

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 14/29
5/28/24, 12:38 AM Nmpy_1
[[10 20]
[30 40]
[50 60]]
40

Accessing element by Slcing on 2-D Array:

Sysntax:

a[row,column]
Row Column

a[begin:end:step , begin:end:step]
In [37]: # applying Slicing
a= np.array([[10,20],[30,40],[50,60],[70,80],[90,100]])
print(a)
print('\n The value is: \n',a[0::2, : ])

[[ 10 20]
[ 30 40]
[ 50 60]
[ 70 80]
[ 90 100]]

The value is:


[[ 10 20]
[ 50 60]
[ 90 100]]

In [50]: # Accessinh the 20,40 only

import numpy as np
a= np.array([[10,20],[30,40],[50,60],[70,80],[90,100]])
print(a)
print("\nThe slice of the given 2-Array is \n", a[0:2,1:2])
print('\n The value is: \n',a[:2,1:])

[[ 10 20]
[ 30 40]
[ 50 60]
[ 70 80]
[ 90 100]]

The slice of the given 2-Array is


[[20]
[40]]

The value is:


[[20]
[40]]

In [60]: import numpy as np


a= np.arange(1,17).reshape(4,4)
print(a)
print('\nEx-1 The required a[:2,:] slice is: \n', a[:2,:])
print('\nEx-2 The Required a[0::3,:] Slice is: \n', a[0::3,:])
print('\nEx-3 The Required a[:, 0:2] Slice is: \n', a[:, 0:2])
print('\nEx-4 The Required a[:, ::2] Slice is: \n', a[:, ::2])
print('\nEx-5 The Required a[1:3,1:3] Slice Is: \n', a[1:3,1:3])
print('\nEx-6 The Required a[0::3,0::3] Slice is: \n', a[0::3,0::3])

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 15/29
5/28/24, 12:38 AM Nmpy_1
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]

Ex-1 The required a[:2,:] slice is:


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

Ex-2 The Required a[0::3,:] Slice is:


[[ 1 2 3 4]
[13 14 15 16]]

Ex-3 The Required a[:, 0:2] Slice is:


[[ 1 2]
[ 5 6]
[ 9 10]
[13 14]]

Ex-4 The Required a[:, ::2] Slice is:


[[ 1 3]
[ 5 7]
[ 9 11]
[13 15]]

Ex-5 The Required a[1:3,1:3] Slice Is:


[[ 6 7]
[10 11]]

Ex-6 The Required a[0::3,0::3] Slice is:


[[ 1 4]
[13 16]]

In [4]: #a= np.array([[[1,2,3],[4,5,6],[7,8,9]],[[10,11,12],[13,14,15],[16,17,18]]])


#a
# create 3-D Array
# Collection of multiple 2-D Array

import numpy as np
a= np.arange(1,25).reshape(2,3,4)
print(a)

array([[[ 1, 2, 3, 4],
Out[4]:
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]],

[[13, 14, 15, 16],


[17, 18, 19, 20],
[21, 22, 23, 24]]])

In [4]: #Accessing element on 3-D Array

import numpy as np
a= np.arange(1,25).reshape(2,3,4)
print(a)
print('\nEx-1 The required a[:,:,0:1] Slice is: \n',a[:,:,0:1])
print('\nEx-2 The Required a[:,:1,:] Slice is: \n', a[:,:1,:])
print('\nEx-3 The Required a[:,0::2,:] Slice is: \n', a[:,0::2,:])
print('\nEx-4 The Required a[:,0:2,1:3] Slice is: \n', a[:,0:2,1:3])
print('\nEx-4 The Required a[:,0::2,::3] Slice is: \n', a[:,0::2,::3])

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 16/29
5/28/24, 12:38 AM Nmpy_1
[[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]

[[13 14 15 16]
[17 18 19 20]
[21 22 23 24]]]

Ex-1 The required a[:,:,0:1] Slice is:


[[[ 1]
[ 5]
[ 9]]

[[13]
[17]
[21]]]

Ex-2 The Required a[:,:1,:] Slice is:


[[[ 1 2 3 4]]

[[13 14 15 16]]]

Ex-3 The Required a[:,0::2,:] Slice is:


[[[ 1 2 3 4]
[ 9 10 11 12]]

[[13 14 15 16]
[21 22 23 24]]]

Ex-4 The Required a[:,0:2,1:3] Slice is:


[[[ 2 3]
[ 6 7]]

[[14 15]
[18 19]]]

Ex-4 The Required a[:,0::2,::3] Slice is:


[[[ 1 4]
[ 9 12]]

[[13 16]
[21 24]]]

Advanced Indexing

1st way
1-D Array

In [11]: # Accessing multiple arbitary elements :

import numpy as np
a= np.arange(1,100,10)
print('The array is: \n',a)
indices= np.array([2,4,5,8])
print('\nThe elements which we are passed the argument is: \n', a[indices])

The array is:


[ 1 11 21 31 41 51 61 71 81 91]

The elements which we are passed the argument is:


[21 41 51 81]

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 17/29
5/28/24, 12:38 AM Nmpy_1

2nd Way
In [19]: import numpy as np
a= np.arange(10,101,10)
print(a)
l=[2,4,5,8]
m=[3,4,9,1] # indeces with no oder
print('To access the arbitary elements present in the array: \n',a[l])
print('To access the arbitary elements present in the array: \n',a[m])

[ 10 20 30 40 50 60 70 80 90 100]
To access the arbitary elements present in the array:
[30 50 60 90]
To access the arbitary elements present in the array:
[ 40 50 100 20]

2-D Array

In [38]: # Accessing arbitary elements in the given 2-D array

import numpy as np
a= np.arange(1,17).reshape(4,4)
print(a)
print('\nThe output..')
print('Ex-1 The Required Arbitary Elements: ',a[[0,1,2,3],[0,1,2,3]])
print('Ex-2 The Required Arbitary Elementes: ',a[[0,1,2,3],[1,3,0,2]])
print('Ex-3 The Required Arbitary Elementes: ',a[[0,1,2,3,3,3,3],[0,0,0,0,1,2,3]])
print('Ex-4 The Required Arbitary Elementes: ',a[[0,0,0,0,1,2,3],[0,1,2,3,3,3,3]])
print('Ex-5 The Required Arbitary Elementes: ',a[[0,0,1,1,2,2,3,3],[0,1,2,3,0,1,1,2

[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]

The output..
Ex-1 The Required Arbitary Elements: [ 1 6 11 16]
Ex-2 The Required Arbitary Elementes: [ 2 8 9 15]
Ex-3 The Required Arbitary Elementes: [ 1 5 9 13 14 15 16]
Ex-4 The Required Arbitary Elementes: [ 1 2 3 4 8 12 16]
Ex-5 The Required Arbitary Elementes: [ 1 2 7 8 9 10 14 15]

3-D Array

In [44]: # Accessing elements on 3-D Aray

import numpy as np
a= np.arange(1,33).reshape(2,4,4)
print(a)
print('Ex-1 The Selected Arbitary Elementes: ',a[[0,1],[1,0],[2,1]])
print('Ex-2 The Selected Arbitary Elementes: ',a[[0,1],[0,2],[2,3]])
print('Ex-3 The Selected Arbitary Elmentes: ',a[[0,1],[1,1],[1,3]])

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 18/29
5/28/24, 12:38 AM Nmpy_1
[[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]

[[17 18 19 20]
[21 22 23 24]
[25 26 27 28]
[29 30 31 32]]]
Ex-1 The Selected Arbitary Elementes: [ 7 18]
Ex-2 The Selected Arbitary Elementes: [ 3 28]
Ex-3 The Selected Arbitary Elmentes: [ 6 24]

Condition Based Selection


In [10]: import numpy as np
a= np.array([10,20,30,40])
print(a)
boolean_array=np.array([True,False,False,True])
print(a[boolean_array]) #wherever True is there the no will come as output.

[10 20 30 40]
[10 40]

In [14]: import numpy as np


a= np.array([10,20,30,40,50,60])
print(a)
print(a>25) # This will rturn the boolean value
boolean_array=a>25 #This will return the vale from the given array
print(a[boolean_array])

[10 20 30 40 50 60]
[False False True True True True]
[30 40 50 60]

In [21]: import numpy as np


a= np.array([10,20,30,40,50,60,75,13])
print(a)
print('\n',a[a>25])
print(a[a%2==0])
print(a[a%2!=0])

[10 20 30 40 50 60 75 13]

[30 40 50 60 75]
[10 20 30 40 50 60]
[75 13]

In [24]: # 2-D array

import numpy as np
a= np.arange(1,37).reshape(6,6)
print(a)
print(a[a%2==0])

[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]
[13 14 15 16 17 18]
[19 20 21 22 23 24]
[25 26 27 28 29 30]
[31 32 33 34 35 36]]
[ 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36]

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 19/29
5/28/24, 12:38 AM Nmpy_1

In [5]: # Numpy array Slicing

import numpy as np
a= np.arange(10,101,10)
print(a)
# Applying Slicing
b=a[0:4]
print(b)
b[2]=100
print(a)
print(a)

[ 10 20 30 40 50 60 70 80 90 100]
[10 20 30 40]
[ 10 20 100 40 50 60 70 80 90 100]
[ 10 20 100 40 50 60 70 80 90 100]

In [16]: # Advanced Indexing and condition based selection

import numpy as np
a= np.arange(10,101,10)
print('a=',a)
b= a[[0,2,3]]
print('b=',b)
# if we want to change in a this will not reflacted to b
a[1]=300
print('After adding the value to a')
print('a=',a)
print('Same time chec the b')
print(b) # The output of b is not reflacted the changed value

#Because b is a separate object.

a= [ 10 20 30 40 50 60 70 80 90 100]
b= [10 30 40]
After adding the value to a
a= [ 10 300 30 40 50 60 70 80 90 100]
Same time chec the b
[10 30 40]

How To Iterate elements of nd Array


Applying Normal Loop:
In [20]: # Iterate element of 1-D Array

import numpy as np
a= np.arange(10,101,10)
print(a)
for x in a:
print(x)

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 20/29
5/28/24, 12:38 AM Nmpy_1
[ 10 20 30 40 50 60 70 80 90 100]
10
20
30
40
50
60
70
80
90
100

In [14]: # TO Iterate elements of 2-D Array

import numpy as np
a= np.array([[10,20,30],[40,50,60],[70,80,90]])
#a= np.arange(10,91,10).reshape(3,3)
print(a)
print('Iterate Each Elements')
for x in a:
for y in x:
print(y)

[[10 20 30]
[40 50 60]
[70 80 90]]
Iterate Each Elements
10
20
30
40
50
60
70
80
90

In [17]: # TO Iterate elements of 3-D Array

import numpy as np
a= np.array([[[10,20],[30,40]],[[50,60],[70,80]]])
#a= np.arange(10,81,10).reshape(2,2,2)
print(a)
for x in a:
for y in x:
for z in y:
print(z)

[[[10 20]
[30 40]]

[[50 60]
[70 80]]]
10
20
30
40
50
60
70
80

Applying nditer()

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 21/29
5/28/24, 12:38 AM Nmpy_1

In [49]: # For 1-D Array

import numpy as np
a= np.arange(10,101,10)
print(a)
for x in np.nditer(a):
print(x)

[ 10 20 30 40 50 60 70 80 90 100]
10
20
30
40
50
60
70
80
90
100

In [36]: # For 2-D Array

import numpy as np
a= np.arange(10,91,10).reshape(3,3)
print(a)
for x in np.nditer(a):
print(x)

[[10 20 30]
[40 50 60]
[70 80 90]]
10
20
30
40
50
60
70
80
90

In [39]: # For 3-D Array

import numpy as np
a= np.arange(10,181,10).reshape(2,3,3)
print(a)
for x in np.nditer(a):
print(x)

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 22/29
5/28/24, 12:38 AM Nmpy_1
[[[ 10 20 30]
[ 40 50 60]
[ 70 80 90]]

[[100 110 120]


[130 140 150]
[160 170 180]]]
10
20
30
40
50
60
70
80
90
100
110
120
130
140
150
160
170
180

In [51]: # For 4-D Array

import numpy as np
a=np.arange(1,17).reshape(2,2,2,2)
print(a)
for x in np.nditer(a):
print(x)

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

[[ 5 6]
[ 7 8]]]

[[[ 9 10]
[11 12]]

[[13 14]
[15 16]]]]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

Iterate Elements of Sliced Array


localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 23/29
5/28/24, 12:38 AM Nmpy_1

In [54]: import numpy as np


a= np.arange(10,91,10).reshape(3,3)
print(a)
for x in np.nditer(a[:,:2]):
print(x)

[[10 20 30]
[40 50 60]
[70 80 90]]
10
20
40
50
70
80

To get elementes in required type Using op_dtypes

In [9]: import numpy as np


a= np.arange(10,91,10).reshape(3,3)
for x in np.nditer(a,flags=['buffered'],op_dtypes=['float']):
print(x)
print('\n There is no imact in the type of original array\n')
print(a)

10.0
20.0
30.0
40.0
50.0
60.0
70.0
80.0
90.0

There is no imact in the type of original array

[[10 20 30]
[40 50 60]
[70 80 90]]

In [18]: #check the type of the given array

import numpy as np
a= np.arange(1,10).reshape(3,3)
print(a)

for x in np.nditer(a):
print(x.dtype)

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

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 24/29
5/28/24, 12:38 AM Nmpy_1

Applying ndenumerate() Function


In [29]: # For 1-D Array

import numpy as np
a= np.arange(1,11)
print(a)

for pos,element in np.ndenumerate(a):


print(f'{element} element present at the position{pos}')
# after{element} we can use , for segrigation

[ 1 2 3 4 5 6 7 8 9 10]
1 element present at the position(0,)
2 element present at the position(1,)
3 element present at the position(2,)
4 element present at the position(3,)
5 element present at the position(4,)
6 element present at the position(5,)
7 element present at the position(6,)
8 element present at the position(7,)
9 element present at the position(8,)
10 element present at the position(9,)

In [33]: # We cn perform any operation here {element*2}

import numpy as np
a= np.arange(1,11)
print(a)

for pos,element in np.ndenumerate(a):


print(f'{element*2} element present at the position{pos}')
print(a)

[ 1 2 3 4 5 6 7 8 9 10]
2 element present at the position(0,)
4 element present at the position(1,)
6 element present at the position(2,)
8 element present at the position(3,)
10 element present at the position(4,)
12 element present at the position(5,)
14 element present at the position(6,)
16 element present at the position(7,)
18 element present at the position(8,)
20 element present at the position(9,)
[ 1 2 3 4 5 6 7 8 9 10]

In [35]: # For 2-D Array

import numpy as np
a= np.arange(10,91,10).reshape(3,3)
for pos,element in np.ndenumerate(a):
print(f"{element} Element present at the posisition {pos}")

10 Element present at the posisition (0, 0)


20 Element present at the posisition (0, 1)
30 Element present at the posisition (0, 2)
40 Element present at the posisition (1, 0)
50 Element present at the posisition (1, 1)
60 Element present at the posisition (1, 2)
70 Element present at the posisition (2, 0)
80 Element present at the posisition (2, 1)
90 Element present at the posisition (2, 2)

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 25/29
5/28/24, 12:38 AM Nmpy_1

In [39]: #For 3-D Array

import numpy as np
a= np.arange(10,181,10).reshape(2,3,3)
for pos,element in np.ndenumerate(a):
print(f"{element} element present at position {pos}")

10 element present at position (0, 0, 0)


20 element present at position (0, 0, 1)
30 element present at position (0, 0, 2)
40 element present at position (0, 1, 0)
50 element present at position (0, 1, 1)
60 element present at position (0, 1, 2)
70 element present at position (0, 2, 0)
80 element present at position (0, 2, 1)
90 element present at position (0, 2, 2)
100 element present at position (1, 0, 0)
110 element present at position (1, 0, 1)
120 element present at position (1, 0, 2)
130 element present at position (1, 1, 0)
140 element present at position (1, 1, 1)
150 element present at position (1, 1, 2)
160 element present at position (1, 2, 0)
170 element present at position (1, 2, 1)
180 element present at position (1, 2, 2)

Arithmetic Operator
Array with Scalar value
In [6]: # 1-D Array

import numpy as np
a= np.arange(1,11)
print(a)
print('\n')
print(f"a+2 value is: {a+2}")
print(f"a-2 value is: {a-2}")
print(f"a*2 value is: {a*2}")
print(f"a/2 value is: {a/2}")
print(f"a//2 value is: {a//2}")
print(f"a%2 value is: {a%2}")

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

a+2 value is: [ 3 4 5 6 7 8 9 10 11 12]


a-2 value is: [-1 0 1 2 3 4 5 6 7 8]
a*2 value is: [ 2 4 6 8 10 12 14 16 18 20]
a/2 value is: [0.5 1. 1.5 2. 2.5 3. 3.5 4. 4.5 5. ]
a//2 value is: [0 1 1 2 2 3 3 4 4 5]
a%2 value is: [1 0 1 0 1 0 1 0 1 0]

In [10]: # 2-D Array

import numpy as np
a= np.arange(10,91,10).reshape(3,3)
print(a)
print('\n')
print(f"a+2 Value is:\n {a+2}")
print(f"a-2 value is:\n {a-2}")
print(f"a*2 value is:\n {a*2}")
localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 26/29
5/28/24, 12:38 AM Nmpy_1
print(f"a/2 value is:\n {a/2}")
print(f"a//2 value is:\n {a//2}")
print(f"a%2 value is:\n {a%2}")

[[10 20 30]
[40 50 60]
[70 80 90]]

a+2 Value is:


[[12 22 32]
[42 52 62]
[72 82 92]]
a-2 value is:
[[ 8 18 28]
[38 48 58]
[68 78 88]]
a*2 value is:
[[ 20 40 60]
[ 80 100 120]
[140 160 180]]
a/2 value is:
[[ 5. 10. 15.]
[20. 25. 30.]
[35. 40. 45.]]
a//2 value is:
[[ 5 10 15]
[20 25 30]
[35 40 45]]
a%2 value is:
[[0 0 0]
[0 0 0]
[0 0 0]]

Array with Array


Note:- To perform this operation in elements "Array with Array" the foolowing statement
must be follow other wise error will be generate

1. Same dimention
2. Same size
3. Same shape

In [20]: # 1-D Array

import numpy as np
a= np.array([10,30,40,50])
b= np.array([60,70,80,90])
print('A= ',a)
print('B= ',b)
print('\n')
print(f"Dimention of A: {a.ndim}, Size of A: {a.shape}, Shape of A: {a.shape}")
print(f"Dimention of A: {b.ndim}, Size of A: {b.shape}, Shape of A: {b.shape}")
print(f"A+B value is: {a+b}")
print(f"A-B value is: {a-b}")
print(f"A*B value is: {a*b}")
print(f"A/B value is: {a/b}")

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 27/29
5/28/24, 12:38 AM Nmpy_1
A= [10 30 40 50]
B= [60 70 80 90]

Dimention of A: 1, Size of A: (4,), Shape of A: (4,)


Dimention of A: 1, Size of A: (4,), Shape of A: (4,)
A+B value is: [ 70 100 120 140]
A-B value is: [-50 -40 -40 -40]
A*B value is: [ 600 2100 3200 4500]
A/B value is: [0.16666667 0.42857143 0.5 0.55555556]

In [41]: #2-D Array

a= np.arange(1,10,1).reshape(3,3)
b= np.arange(10,91,10).reshape(3,3)
print('A= \n',a)
print('B= \n',b)
print(f"A+b value is: \n{a+b}")
print(f"A-b value is: \n{a-b}")
print(f"A*B value is: \n{a*b}")

A=
[[1 2 3]
[4 5 6]
[7 8 9]]
B=
[[10 20 30]
[40 50 60]
[70 80 90]]
A+b value is:
[[11 22 33]
[44 55 66]
[77 88 99]]
A-b value is:
[[ -9 -18 -27]
[-36 -45 -54]
[-63 -72 -81]]
A*B value is:
[[ 10 40 90]
[160 250 360]
[490 640 810]]

In [51]: # By using the inbuilt fnction

import numpy as np
a= np.array([10,30,40,50])
b= np.array([60,70,80,90])
print('A= ',a)
print('B= ',b)
print(F"Demention of A: {a.ndim}, Size of A is: {a.shape}, Shape of A: {a.shape}")
print(F"Demention of B: {b.ndim}, Size of B is: {b.shape}, Shape of B: {b.shape}")
print(F'A+B value is: {np.add(a,b)}')
print(F'A-B value is: {np.subtract(a,b)}')
print(F'A*B value is: {np.multiply(a,b)}')
print(F'A/B value is: {np.divide(a,b)}')
print(F'A%B value is: {np.mod(a,b)}')

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 28/29
5/28/24, 12:38 AM Nmpy_1
A= [10 30 40 50]
B= [60 70 80 90]
Demention of A: 1, Size of A is: (4,), Shape of A: (4,)
Demention of B: 1, Size of B is: (4,), Shape of B: (4,)
A+B value is: [ 70 100 120 140]
A-B value is: [-50 -40 -40 -40]
A*B value is: [ 600 2100 3200 4500]
A/B value is: [0.16666667 0.42857143 0.5 0.55555556]
A%B value is: [10 30 40 50]

localhost:8888/nbconvert/html/Nmpy_1.ipynb?download=false 29/29

You might also like