Practical.
No : 01
#Name:____________________________________
#Class: S.E (E & TC) Roll No: _________________
#Subject: Python – Data Analytics Lab.
#1. Python Program to Demonstrate basic Array Characteristics
import numpy as np
#create array object
arr=np.array([[1,2,3],[4,2,5]])
#Printing type of Object
print("Array is of type: ", type(arr))
#Printing array diamensions
print("No of Diamensions:", arr.ndim)
#printing array shape
print("Shape of Array:", arr.shape)
#printing array size
print("Size of Array:", arr.size)
#printing type of elements in array
print("Array stores elements of type:", arr.dtype)
OUTPUT:
Array is of type: <class 'numpy.ndarray'>
No of Diamensions: 2
Shape of Array: (2, 3)
Size of Array: 6
Array stores elements of type: int64
#2. Python Program to Demonstrate Unary Operators in numpy
import numpy as np
arr=np.array ([[1,5,6], [4,7,2], [3,1,9]])
#maximum element of array
print("Largest element of Array:", arr.max())
#Row-wise maximum elements of array
print("Row-wise maximum element:", arr.max(axis=0))
#Coloumn-wise minimum elements of array
print("Coloumn-wise minimum element:", arr.min(axis=1))
#Sum of array elements
print("Sum of array elements:", arr.sum())
OUTPUT:
Largest element of Array: 9
Row-wise maximum element: [4 7 9]
Coloumn-wise minimum element: [1 2 1]
Sum of array elements: 38
#3. Python Program to Demonstrate Binary Operators in numpy
Import numpy as np
a=np.array([[1,2],[3,4]])
b=np.array([[4,3],[2,1]])
#Add Arrays
print("Array Sum:\n", a+b)
#Multiply Arrays
print("Array Multiplication:\n", a*b)
#Matrix Multiplication
print("Matrix Multiplication:\n", a.dot(b))
OUTPUT:
Array Sum:
[[5 5]
[5 5]]
Array Multiplication:
[[4 6]
[6 4]]
Matrix Multiplication:
[[ 8 5] [20 13]]
#4. Python Program to Demonstrate
Import numpy as np
#creating array from list type float
a=np.array ([[1,2,4],[5,8,7]], dtype=’float’)
print(“Array created using passed list:\n”, a)
#creating array from tuple
b=np.array((1,3,2))
print(“Array created using tuple:\n”, b)
#creating a 3x4 array with all zeroes
c =np.zeros((3,4))
print(“\nArray initialized with all zeros:\n”, c)
#create an array with random values
d =np.random.random((2,2))
print(“An random Array is: “, d)
#creating a sequence of integers
#from 0 to 40 with steps of 5
f =np.arange (0,40,5)
print(“An sequential array by steps of 5:\n”, f)
#reshaping 3x4 array to 2x2x3 array
arr =np.array([[4,5,6,2],[1,2,3,4],[1,5,0,4]])
newarr = arr.reshape(2,2,3)
print(“original array:\n”, arr)
print(“Reshaped array:\n”, newarr)
#creating an flatten array
arr =np.array([[1,2,3],[4,5,6]])
flat = arr.flatten()
print(“\nOriginal Array:\n”, arr)
print(“\nFlatten array:\n”, flat)
OUTPUT:
Array created using passed list:
[[1 2 4]
[5 8 7]]
Array created using tuple:
[1 3 2]
Array initialized with all zeros:
[[0 0 0 0]
[0 0 0 0]
[0 0 0 0]]
An Random array is:
[[0.4254631 0.4589615]
[0.2568947 0.4589632]]
A sequential array with steps of 5:
[0 5 10 15 20 20 30 35]
Original Array:
[[4,5,6,2]
[1,2,3,4]
[1,5,0,4]]
Reshaped Array:
[[4,5,6]
[2,1,2]
[3,4,1]
[5,4,0]]
Original Array:
[[1 2 3]
[4 5 6]]
Flattened Array:
[1 2 3 4 5 6]
# Python program to demonstrate unary operators in numpy
import numpy as np
arr = np.array([[1, 5,
6],
[4, 7, 2],
[3, 1, 9]])
# maximum element of array
print ("Largest element is:", arr.max())
print ("Row-wise maximum elements:",arr.max(axis = 1))
# minimum element of array
print ("Column-wise minimum elements:",arr.min(axis = 0))
# sum of array elements
print ("Sum of all array elements:",arr.sum())
OUTPUT:
Array is of type: <class 'numpy.ndarray'>
No. of dimensions: 2
Shape of array: (2, 3)
Size of array: 6
Array stores elements of type: int64
# PANDAS AND PANDAS - DATAFRAME
import pandas as pd
data = [['Alex',10],['Bob',12],['Clarke',13]]
df = pd.DataFrame(data,columns=['Name','Age'],dtype=float)
print (df)
OUTPUT:
Name Age
0 Alex 10.00
1 Bob 12.00
2 Clarke 13.00
#Viewing the first n rows
import pandas as pd
data = [['Alex',10],['Bob',12],['Clarke',13]]
df=pd.DataFrame(data,columns=['Name','Age'],
dtype=float) print (df)
print(df.head () )
OUTPUT:
Name Age
0 Alex 10.00
1 Bob 12.00
#Print a concise summary of a DataFrame
import pandas as pd
data = [['Alex',10],['Bob',12],['Clarke',13]]
df =
pd.DataFrame(data,columns=['Name','Age'],dtype=fl
oat) print (df)
Print(df. Info ())
OUTPUT:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
# Column Non-Null Count Dtype
--- ---- --- --- --- --- --- --- --- --- ---
0 Name 3 non-null object
1 Age 3 non-null float64
dtypes:
float64(1),object(1)
memory usage:
176.0+ bytes None
#Calculating Some Statistical Data like Percentile, Mean and Std of the
Numerical
print ( df.describe () )
Age
Count 3.000000
Mean 11.666667
Std 1.527525
Min 10.000000
25% 11.000000
50% 12.000000
75% 12.000000
max 13.000000
#Selecting Coloumn
Print( df [‘Name’])
OUTPUT:
0 Alex
1 Bob
2 Clarke
Name: Name,
dtype:object
#Selecting Row
Print (df. Iloc [2] )
OUTPUT:
Name Clarke
Age 13
Name: 2, dtype:object
#Importing and Exporting Data in Python
#Reading and Writing CSV Files in Python With pandas
Name,Hire Date,Salary,Sick Days remaining
Graham Chapman,03/15/14,50000.00,10
JohnCleese,06/01/15,65000.00,8
EricIdle,05/12/14,45000.00,10
TerryJones,11/01/13,70000.00,3
TerryGilliam,08/12/14,48000.00,7
MichaelPalin,05/23/13,66000.00,8
#Reading the CSV into a DataFrame
import pandas
df=pandas.read_csv('hrdata.
csv') print(df)
OUTPUT:
Name Hire Date Salary Sick Days
0 Graham Chapman 03/15/14 remaining 50000.0 10
1 John Cleese 06/01/15 65000.0 8
2 Eric Idle 05/12/14 45000.0 10
3 Terry Jones 11/01/13 70000.0 3
4 Terry Giliam 08/12/14 48000.0 7
5 Michael Palin 05/23/13 66000.0 8
#Writing CSV Files With pandas
import pandas as pd
cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4'], 'Price':
[22000,25000,27000,35000]}
df = pd.DataFrame(cars, columns= ['Brand', 'Price'])
df.to_csv (r'C:\Users\Ron\Desktop\export_dataframe.csv', index =
False, header=True)
print (df)
#DB-API 2.0 interface for SQLite databases
import sqlite3
conn=sqlite3.connect('example
.db')
c = conn.cursor()
# Create table c.execute
('''CREATE TABLE
stock(date text, trans
text, symbol text, qty
real, price real)''')
# Insert a row of data
c.execute("INSERT INTO stock VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
c.execute("INSERT INTO stock VALUES ('2006-03-28', 'BUY', 'IBM', 1000, 45.00)")
c.execute("INSERT INTO stock VALUES ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00)")
# Save (commit) the
changes
conn.commit()
for row in c.execute('SELECT * FROM stock ORDER BY
price'): print(row)
# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
conn.close()
OUTPUT:
('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
('2006-03-28', 'BUY', 'IBM', 1000.0, 45.0)
('2006-04-05', 'BUY', 'MSFT', 1000.0, 72.0)