Python Unit 5
Python Unit 5
Python Unit 5
Data types and objects, loading packages, namespaces, Reading and writing data, Simple
plotting, Control flow, Debugging, Code profiling, Acquiring Data with Python:Loading from
CSV files, Accessing SQL databases, Cleansing Data with Python:Stripping out extraneous
information, normalizing data, Formatting data.
Q. Questions Mark
No s
.
1 What are CSV Files? 2
The use of the comma as a field separator is the source of the name
for this file format.For working CSV files in python, there is an
inbuilt module called csv.
SN Name City
2 Jack California
3 Donald Texas
Example:
# importing line_profiler module
Output:
Python has inbuilt module i.e CSV, which is used for working with
CSV files. In python, we use csv.reader module to read a CSV file.
Example : Reading a CSV file using csv.reader
Here we are going to show how you can read a people.csv file, that
we created in above example.
import csv
withopen('people.csv','r')as csvFile:
reader =csv.reader(csvFile)
for row in reader:
print(row)
Syntax : object.plot(parameters)
Syntax : object.hist(parameters).
3. Bar charts : The bar graphs are used in data comparison where
we can measure the changes over a period of time. It can be
represented horizontally or vertically. Longer the bar it has the
greater the value it contains.
Syntax : object.bar(parameters).
Syntax : object.scatter(parameters).
Program
importMySQLdb
# Open database connection
db=MySQLdb.connect("localhost","testuser","test123","TESTDB")
# prepare a cursor object using cursor() method
cursor =db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql="""INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
The use of the comma as a field separator is the source of the name
for this file format.For working CSV files in python, there is an
inbuilt module called csv.
SN Name City
2 Jack California
3 Donald Texas
We can represent the above table in CSV as :
SN, Name, City
1, Michael, New Jersey
2, Jack, California
3, Donald, Texas
Python has inbuilt module i.e CSV, which is used for working with
CSV files. In python, we use csv.reader module to read a CSV file.
Example : Reading a CSV file using csv.reader
Here we are going to show how you can read a people.csv file, that
we created in above example.
import csv
withopen('people.csv','r')as csvFile:
reader =csv.reader(csvFile)
for row in reader:
print(row)
withopen('person.csv','w')as csvFile:
writer =csv.writer(csvFile)
writer.writerows(csvData)
Program
# importing the required module
import matplotlib.pyplot as plt
# x axis values
x = [1,2,3,4]
# corresponding y axis values
y = [0,100,200,300]
# plotting the points
plt.plot(x, y)
# naming the x axis
plt.xlabel('Time ')
# naming the y axis
plt.ylabel('Position ')
# giving a title to my graph
plt.title('Visualizing Time and Position Graph!')
# function to show the plot
plt.show()
Output :
13 Plot a bar graph for the following rainfall data. Give appropriate 10
name for x- axis and y axis. Give a title to the graph.
Chennai 50cms
Thiruvallur 45 cms Kanchipurram 55cms Arakkonam 32 cms
Program
import matplotlib.pyplot as plt
# x-coordinates of left sides of bars
left = [1, 2, 3, 4]
# heights of bars
height = [50, 45, 55, 32]
# labels for bars
tick_label = ['chennai', 'thiruvallur', 'kanchipuram', 'Arakonnam']
# plotting a bar chart
plt.bar(left, height, tick_label = tick_label, width = 0.8, color = ['re
d', 'green'])
# naming the x-axis
plt.xlabel('District')
# naming the y-axis
plt.ylabel('Rainfall in cms')
# plot title
plt.title('District- Rainfall!')
# function to show the plot
plt.show()
Output:
Program
import matplotlib.pyplot as plt
# x-axis values
x = [1,2,3,4,5,6,7,8,9,10]
# y-axis values
y = [2,4,5,7,6,8,9,11,12,12]
# plotting points as a scatter plot
plt.scatter(x, y, color= "red", marker= "*", s=30)
# x-axis label
plt.xlabel('x - axis chart')
# frequency label
plt.ylabel('y - axis chart')
# plot title
plt.title('My scatter plot visualization!')
# showing legend
plt.legend()
# function to show the plot
plt.show()
Output
import mysql.connector
db = mysql.connector.connect(
host = "localhost",
user = "yourusername",
password = "yourpassword",
database = "studytonight"
)
If the above code is executed without any errors then it means
you have successfully connected to the database
named studytonight.
SQL Query to Create Table
db = mysql.connect(
host = "localhost",
user = "yourusername",
passwd = "yourpassword",
database="studytonight"
)
cursor = db.cursor()
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
mycursor = mydb.cursor()
Creating a Table
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="student"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE stud (name
VARCHAR(255), regno int, grade VARCHAR(5))")
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="student"
)
mycursor = mydb.cursor()
mydb.commit()
print(mycursor.rowcount, "record inserted.")
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="student"
)
mycursor = mydb.cursor()
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Program
import matplotlib.pyplot as plt
# defining labels
activities = ['eat', 'sleep', 'work', 'play' ,'mediate']
# portion covered by each label
slices = [15, 30, 20, 12, 13]
# color for each label
colors = ['r', 'y', 'g', 'b','m']
# plotting the pie chart
plt.pie(slices, labels = activities, colors=colors, startangle=90, shad
ow = True,radius = 1.2)
# plotting legend
plt.legend()
# showing the plot
plt.show()
Output
Creating a Database
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")
Creating a Table
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mydb.commit()
print(mycursor.rowcount, "record inserted.")
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Output :
Update Table
You can update existing records in a table by using the "UPDATE"
statement:
Example
Overwrite the address column from "Valley 345" to "Canyoun
123":
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
Output
Delete Record
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")
Output