kumarpac / pythonbasicprogram

0 stars 0 forks source link

NumPy #1

Open kumarpac opened 3 days ago

kumarpac commented 3 days ago

This is exclusively training program for NumPy

What is NumPy? It's numerical python package, built on top of C language.

Data Type Vs Data Structure Data type can be int, str, float, bool, list, tuple, dict and set

Data Structure is a method to organize and manage data, it enables to store and allows computations

NumPy is an open source, used to work with arrays.

Key features of NumPy

  1. Create N dimensional array, also called Nd array.
  2. Broadcasting- Universal functions(Ufuncs)
  3. Efficient computation( Vectorization )
  4. Linear Algebra

NumPy official documents https://numpy.org/ latest release is 2.0

Array looks like list, only difference, it explicitly shows array

import numpy as np print(np.array([1,2,4])) #1D print(np.array([[1,2],[2,3]])) #2D print(np.array([[[1,2,3],[4,5,6],[7,8,9]]])) #3D [1 2 4] [[1 2] [2 3]] [[[1 2 3] [4 5 6] [7 8 9]]]

a= [[1,2,3,4],[5,6,7,8]] #what would be the length len(a) 2

How to recognize list is 1d or 2d, the best way to have a look at the starting of the list, how many square brackets it contains.

list_2d=[[1,2,3,4],[5,6,7,8],[9,10,11,12]]

print(list_2d) #[[1,2,3,4],[5,6,7,8],[9,10,11,12]]

print(list_2d[0]) #[1, 2, 3, 4]

for i in list_2d: print(i)

""" [1, 2, 3, 4] [5, 6, 7, 8] [9, 10, 11, 12] """

for i in list_2d: for j in i: print(j)

] """

for i in list_2d: for j in i: print(j)

output [1, 2, 3, 4] [5, 6, 7, 8] [9, 10, 11, 12] 1 2 3 4 5 6 7 8 9 10 11 12

example of 3d array

list_3d=[ [ [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] ] ]

len(list_3d) #3

list_3d[0][0][1] #2

for i in list_3d: print(i)

[[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]]

for i in list_3d: print(i[0])

[1, 2, 3] [10, 11, 12] [19, 20, 21]

for i in list_3d: for j in i: print(j) 7] 0s for i in list_3d: for j in i: print(j)

[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]

for i in list_3d: for j in i: for k in j: print(k)

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

list_3d[1][2][1]=100 list_3d [[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 11, 12], [13, 14, 15], [16, 100, 18]], [[19, 20, 21], [22, 23, 24], [25, 26, 27]]]

Note: whenever you do slicing of the element it never gives out of index error. but during indexing it gives index out or range error Ex: list_2d=[ [1,2,3,4], [5,6,7,8], [9,10,11,12] ]

list_2d[1:2] #[[5, 6, 7, 8]]

list_2d[1:2][1:4] #[] No error during slicing of the list

list_2d[3] #IndexError: list index out of range