NumPy Creating Arrays
2 D Array
import numpy as np
arr1=np.array([1,2,3])
arr1
OUTPUT:
array([1, 2, 3])
type(arr1)
OUTPUT:
numpy.ndarray
arr1.ndim
OUTPUT:
1
arr1.size
OUTPUT:
3
arr1.shape
(3,)
Creating 2-D Array
arr = np.array([ [1,1,1] ,[2,2,2] ,[3,3,3] , [4,4,4] ])
print(arr)
OUTPUT:
[[1 1 1]
[2 2 2]
[3 3 3]
[4 4 4]]
arr.shape
OUTPUT:
(4,3)
arr.size
OUTPUT:
12
arr.ndim
OUTPUT:
2
Class and Attributes of nd array,Size and shape of a numpy array
list3 = [ [1, 2, 3, 4],[5, 6, 7, 8], [9, 10, 11, 12] ]
arr = np.array(list3, dtype ='str')
print(arr)
OUTPUT:
[['1' '2' '3' '4']
['5' '6' '7' '8']
['9' '10' '11' '12']]
arr.dtype
OUTPUT:
dtype('<U2')
arr.size
OUTPUT:
12
arr.ndim
OUTPUT:
2
Accessing 2-D array Indexing
list3 = [[1, 2, 3, 4],[5, 6, 7, 8], [9, 10, 11, 12]]
arr = np.array(list3)
print(arr)
OUTPUT:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
arr[ 0:2 , 2:4 ]
OUTPUT:
array([[3, 4],
[7, 8]])
print("First Row:",arr[0])
print("Last Row:",arr[-1])
print("Single Element",arr[2,3])
print("All Rows but Second colums",arr[:,2])
print("Second Row and all colums",arr[2,:])
print("All rows but only columns from 1 to 3\n",arr[:,1:3])
OUTPUT:
First Row: [1 2 3 4]
Last Row: [ 9 10 11 12]
Single Element 12
All Rows but Second colums [ 3 7 11]
Second Row and all colums [ 9 10 11 12]
All rows but only columns from 1 to 3
[[ 2 3]
[ 6 7]
[10 11]]
Lesson Assignment
Challenge yourself with our lab assignment and put your skills to test.
# Python Program to find the area of triangle
a = 5
b = 6
c = 7
# Uncomment below to take inputs from the user
# a = float(input('Enter first side: '))
# b = float(input('Enter second side: '))
# c = float(input('Enter third side: '))
# calculate the semi-perimeter
s = (a + b + c) / 2
# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)