Here i like to show some examples using NumPy, Please copy and paste the codes in your environement to practice
Note: The below examples are made for practice purpose, so not much details are given. Better suited for the experienced learners as refreshement
NumPy Examples
my_list = [x*10 for x in range(1, 11)]
my_array = np.array(my_list)
array([ 10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
sales_array.ndim #Has 1 dimension
sales_array.shape #Gives shape of array
(10,)
sales_array.size
10
my_array.dtype
a=np.array(range(6)) # Creating a 1D array
new2darray=np.array([list(range(5)),list(range(5))]) # use [] to get create 2D data from lists
new2darray=(new2darray *10) #No need to loop through to perform operations
new2darray.T # perform transpose
new2darray.dtype #Gives data type
my_array.reshape(10,1) # Reshape #Transpose to multi dimension matrix
np.ones(5, dtype=int) #Create a array with ones
np.ones((2,3), dtype=int) #Create a 2d array with 1
np.zeros((2,3), dtype=int) #Create a 2d matrix with 0’s
np.arange(10,21) #create a range of elements in array
np.arange(10,21,5) #create a range of numbers with 5 as step
np.arange(10) #by default starts from zero to n-1
np.linspace(2,3,num=5, retstep=True) #create a numbers from 2 to 3 with 5 values, retstep shows step value
np.linspace(2,3,num=5, endpoint=False) # endpoint=False ignore last/stop digit
np.arange(10).reshape(2,5)
np.ones(10, dtype=int).reshape(2,5)
np.identity(10)
rng = np.random.default_rng(6688) #Get random value from seed
rng.random(10) #Generate 10 random values using seed
rng.integers(1,5,8) #Genrate random 10 integers where start point is 1 and endpoint is 5
rng.normal(50,5,10) #Generate 10 normal distributed numbers where mean is 50(centred around 50) std deviation as 5
np.arange(10,101,10, dtype=float).reshape(5,2)
np.linspace(10,100,10).reshape(5,2)
(np.arange(1,11)*10).reshape(5,2)
rng = np.random.default_rng(6688)
rng.random(9).reshape(3,3)
rng = np.random.default_rng(2022)
rng.random((3,3))
fruits = list([“apple”, “banana”, “orange”, “ma2ngo”, “pineapple”, “pear”, “avacado”, “guava”, “watermelon”, “grapes”])
fruits[0]
fruits[-1]
fruits[1::2] #Start with 1st element with step size of 2
fruits[::2] #Start with 0th eleement end with last element with step size of 2
Indexing and slicing arrays
fruits2d = np.array(fruits).reshape(2,5)
fruits2d
array([[‘apple’, ‘banana’, ‘orange’, ‘ma2ngo’, ‘pineapple’],
[‘pear’, ‘avacado’, ‘guava’, ‘watermelon’, ‘grapes’]], dtype='<U10′)
fruits2d[1,0]
fruits2d[:,2]
fruits2d[:,2:]
array([[‘orange’, ‘ma2ngo’, ‘pineapple’],
[‘guava’, ‘watermelon’, ‘grapes’]], dtype='<U10′)
# [:, 2:]: This is a slicing operation:
# : in the first dimension ([:, … ]) selects all rows (from the beginning : to the end :).
# 2: in the second dimension ([ …, 2:]) selects elements from the third column (index 2) onwards (until the end :).
fruits2d[: :,2: :]
array([[‘orange’, ‘ma2ngo’, ‘pineapple’],
[‘guava’, ‘watermelon’, ‘grapes’]], dtype='<U10′)
fruits2d[0,:]
array([‘apple’, ‘banana’, ‘orange’, ‘ma2ngo’, ‘pineapple’], dtype='<U10′)
fruits2d[1,:]
array([‘pear’, ‘avacado’, ‘guava’, ‘watermelon’, ‘grapes’], dtype='<U10′)
fruits2d[:,:]
array([[‘apple’, ‘banana’, ‘orange’, ‘ma2ngo’, ‘pineapple’],
[‘pear’, ‘avacado’, ‘guava’, ‘watermelon’, ‘grapes’]], dtype='<U10′)
fruits2d[:,0:]
array([[‘apple’, ‘banana’, ‘orange’, ‘ma2ngo’, ‘pineapple’],
[‘pear’, ‘avacado’, ‘guava’, ‘watermelon’, ‘grapes’]], dtype='<U10′)
fruits2d[:,1:]
array([[‘banana’, ‘orange’, ‘ma2ngo’, ‘pineapple’],
[‘avacado’, ‘guava’, ‘watermelon’, ‘grapes’]], dtype='<U10′)
fruits2d[:,0:3]
array([[‘apple’, ‘banana’, ‘orange’],
[‘pear’, ‘avacado’, ‘guava’]], dtype='<U10′)
fruits2d[:,0::2]
# [(rows) start:end:intervals/step, (columns) start:end:intervals/step]
array([[‘apple’, ‘orange’, ‘pineapple’],
[‘pear’, ‘guava’, ‘grapes’]], dtype='<U10′)
fruits2d[:,3]
array([‘ma2ngo’, ‘watermelon’], dtype='<U10′)
fruits2d[:,0]
array([‘apple’, ‘pear’], dtype='<U10′)
fruits2d[:,1:3]
array([[‘banana’, ‘orange’],
[‘avacado’, ‘guava’]], dtype='<U10′)
Array operations
sales1 = np.array([0,5,111,0,518,324,435,4545,23]).reshape(3,3)
sales1
array([[ 0, 5, 111],
[ 0, 518, 324],
[ 435, 4545, 23]])
sales1 +2
array([[ 2, 7, 113],
[ 2, 520, 326],
[ 437, 4547, 25]])
qty = sales1[0,:]
price = sales1[1,:]
print(sales1)
[[ 0 5 111]
[ 0 518 324]
[ 435 4545 23]]
print(qty)
[ 0 5 111]
print(price)
[ 0 518 324]
print(qty*price)
[ 0 2590 35964]
(qty*price).sum()
38554
[x*y for x,y in zip(qty,price)] #Alternate we can generate same using python
[0, 2590, 35964]
[x + 2 for x in qty] #Alternate
[2, 7, 113]
Or
newqty = [] #Alternate
for x in qty:
newqty.append(x+2)
newqty
[2, 7, 113]
sales1.reshape(9) #convert 2d to 1d
Filtering Array
sales1
array([[ 0, 5, 111],
[ 0, 518, 324],
[ 435, 4545, 23]])
sales1 !=0
array([[False, True, True],
[False, True, True],
[ True, True, True]])
sales1[sales1 !=0]
array([ 5, 111, 518, 324, 435, 4545, 23])
sales1[(sales1 == 0) | (sales1 ==5)] #Or | operator or pipe operatot, similary we can use & for and operator
array([0, 5, 0])
mask = (sales1 == 0) | (sales1 ==5) # Use variable to keep it simple
sales1[mask]
even_odd = np.array([‘even’,’odd’]*5)
print(even_odd)
[‘even’ ‘odd’ ‘even’ ‘odd’ ‘even’ ‘odd’ ‘even’ ‘odd’ ‘even’ ‘odd’]
print(even_odd != ‘odd’)
[ True False True False True False True False True False]
print(even_odd[even_odd != ‘odd’])
[‘even’ ‘even’ ‘even’ ‘even’ ‘even’]
my_array = np.arange(1,11)
print(my_array)
[ 1 2 3 4 5 6 7 8 9 10]
my_array[even_odd !=’odd’] = 0
print(my_array)
[ 0 2 0 4 0 6 0 8 0 10]
my_array[0]=100
print(my_array)
[100 2 0 4 0 6 0 8 0 10]
Where function
print(my_array)
[100 2 0 4 0 6 0 8 0 10]
np.where(my_array >0, “instock”, “out of stock”)
array([‘instock’, ‘instock’, ‘out of stock’, ‘instock’, ‘out of stock’,
‘instock’, ‘out of stock’, ‘instock’, ‘out of stock’, ‘instock’],
dtype='<U12′)
print(my_array)
[100 2 0 4 0 6 0 8 0 10]
print(np.where(my_array >0, “instock”, “out of stock”))
[‘instock’ ‘instock’ ‘out of stock’ ‘instock’ ‘out of stock’ ‘instock’
‘out of stock’ ‘instock’ ‘out of stock’ ‘instock’]
fruits = list([“apple”, “banana”, “orange”, “mango”, “pineapple”, “pear”, “avacado”, “guava”, “watermelon”, “grapes”])
print(fruits)
np.where(my_array >0, “instock”, fruits)
array([‘instock’, ‘instock’, ‘orange’, ‘instock’, ‘pineapple’, ‘instock’,
‘avacado’, ‘instock’, ‘watermelon’, ‘instock’], dtype='<U10′)
np.where(my_array >0, “instock”, np.where(my_array == 100, my_array, 9000))
array([‘instock’, ‘instock’, ‘9000’, ‘instock’, ‘9000’, ‘instock’, ‘9000’,
‘instock’, ‘9000’, ‘instock’], dtype='<U11′)
np.where(my_array >0, 1,0)
array([1, 1, 0, 1, 0, 1, 0, 1, 0, 1])
Array Aggregation
print(my_array.sum())
print(my_array.mean())
print(my_array.max())
print(my_array.min())
print(my_array.std())
print(my_array.argmax())
print(my_array.argmin())
sales1 = np.array([0,5,111,0,518,324,435,4545,23]).reshape(3,3)
print(sales1)
[[ 0 5 111]
[ 0 518 324]
[ 435 4545 23]]
print(sales1.sum(axis=0)) #Aggregates across rows
[ 435 5068 458]
print(sales1.mean(axis=0).round(1))
[ 145. 1689.3 152.7]
Array Functions
print(np.median(sales1))
print(np.percentile(sales1,90).round(2))
print(np.unique(sales1))
print(np.sqrt(sales1).round(2))
Sort
print(sales1)
print(np.sort(sales1))
# a=sales1.sort(axis=0) #sort by columns
sales1[::-1] #reverses
Vectorization and Broadcasting
np.array([100,200,300]).reshape(3,1)
# Broadcasting
print(sales1)
print(sales1 +1)
print(sales1 + [3,2,1]) #adds to respective column
print(sales1 + np.array([100,200,300]))
print(sales1 + np.array([100,200,300]).reshape(3,1))
test_array = np.array([[1,2,3],[1,2,3],[1,2,3]])
print(test_array)
print(test_array[0,:])
print(test_array[:,1])
print(test_array[:,1].reshape(3,1))
print(test_array[0,:] + test_array[:,1].reshape(3,1))
print(np.ones((2,3,3), dtype=int))
[[[1 1 1]
[1 1 1]
[1 1 1]]
[[1 1 1]
[1 1 1]
[1 1 1]]]
print(np.ones(3, dtype=int))
[1 1 1]
print(np.ones((2,3,3), dtype=int) + np.ones(3, dtype=int))
[[[2 2 2]
[2 2 2]
[2 2 2]]
[[2 2 2]
[2 2 2]
[2 2 2]]]