0% found this document useful (0 votes)
6 views

python a2

The document provides Python code for creating and managing a MySQL database using the mysql-connector-python package, including connection setup, table creation, data insertion, and data extraction. It also demonstrates data analysis and visualization using NumPy, Pandas, and Matplotlib, covering data loading, exploration, manipulation, and visualization techniques. Additional considerations for error handling, customization, scalability, and integration with NumPy are mentioned for effective data analysis.

Uploaded by

nishita6978
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

python a2

The document provides Python code for creating and managing a MySQL database using the mysql-connector-python package, including connection setup, table creation, data insertion, and data extraction. It also demonstrates data analysis and visualization using NumPy, Pandas, and Matplotlib, covering data loading, exploration, manipulation, and visualization techniques. Additional considerations for error handling, customization, scalability, and integration with NumPy are mentioned for effective data analysis.

Uploaded by

nishita6978
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

ASSIGNMENT – 2

Here's the Python code that creates a database, populates it


with data, and then extracts the data using the mysql-
connector-python package:
CODE:
import mysql.connector
# Database connection details
db_name = "Mydb"
db_user = "your_username"
db_password = "your_password"
db_host = "localhost"

# Connect to the database


try:
connection = mysql.connector.connect(
host=db_host, user=db_user, password=db_password,
database=db_name
)
print("Connected to database successfully!")
except mysql.connector.Error as err:
print("Error connecting to database:", err)
exit()

# Create a cursor object


cursor = connection.cursor()
# Create the table (omit if the table already exists)
create_table_query = """
CREATE TABLE IF NOT EXISTS users (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE
)
"""
cursor.execute(create_table_query)
connection.commit()

# Insert sample data


insert_query = "INSERT INTO users (name, email) VALUES (%s,
%s)"
values = [("John Doe", "[email protected]"), ("Jane Doe",
"[email protected]")]
cursor.executemany(insert_query, values)
connection.commit()

# Extract data from the table


select_query = "SELECT * FROM users"
cursor.execute(select_query)
result = cursor.fetchall()

# Print the extracted data


print("Extracted data:")
for row in result:
print(f"ID: {row[0]}, Name: {row[1]}, Email: {row[2]}")

# Close the connection


cursor.close()
connection.close()
print("Connection closed successfully!")

This code first imports the mysql.connector package. Then, it


defines the database connection details, including the database
name, username, password, and host. It attempts to connect to the
database and throws an error if the connection fails.

Once connected, it creates a cursor object for interacting with the


database. The code then creates the table named "users" with
columns for ID, name, and email (if it doesn't already exist). It then
inserts two sample records into the table.

Finally, the code executes a query to select all data from the "users"
table, fetches the results into a list, and iterates through each row,
printing the extracted data.

Important:

1. Replace your_username and your_password with your actual


MySQL credentials.

2. Make sure you have the mysql-connector-python package


installed. You can install it using the command pip install
mysql-connector-python.
ASSIGNMENT – 3
Here's a comprehensive example demonstrating the
usage of NumPy, Pandas, and Matplotlib for data
analysis and visualization:
1. Import Libraries:
CODE:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

2. Load Sample Dataset:


While this example uses a pre-defined dataset for demonstration,
remember that you can:

 Load data from various sources:


Replace the sample data with your preferred dataset format (CSV,
Excel, databases, etc.) using relevant libraries like
pandas.read_csv(), pandas.read_excel(), or database
connectors.

 Create custom datasets:


If you don't have existing data, create a list of dictionaries as shown
below, tailoring it to your specific analysis needs.

# Sample data as a list of dictionaries


data = [
{"Country": "China", "Population": 1444, "Continent": "Asia"},
{"Country": "India", "Population": 1380, "Continent": "Asia"},
{"Country": "United States", "Population": 334, "Continent": "North
America"},
{"Country": "Indonesia", "Population": 273, "Continent": "Asia"},
{"Country": "Brazil", "Population": 212, "Continent": "South America"},
]

# Create a Pandas DataFrame from the data


df = pd.DataFrame(data)

3. Explore the Data (Pandas):


Obtain basic information:
CODE:
print(df.info())
print(df.head(3)) # View the first 3 rows

 Get descriptive statistics:


CODE:
print(df.describe(include='all')) # Include
categorical data

4. Data Manipulation (Pandas):


 Filter data:
CODE:
# Filter countries with population above 500
million
df_filtered = df[df['Population'] > 500]
print(df_filtered)

 Create or modify columns:


CODE:
# Add a new column named 'Density' (assuming
population density is hypothetical)
df['Density'] = df['Population'] / 10000
print(df)

5. Data Visualization (Matplotlib):


 Bar chart:
CODE:
plt.figure(figsize=(10, 6))
plt.bar(df['Country'], df['Population'])
plt.xlabel('Country')
plt.ylabel('Population (Millions)')
plt.title('Population Comparison of Selected
Countries')
plt.xticks(rotation=45) # Rotate x-axis labels
for better readability
plt.tight_layout()
plt.show()

 Scatter plot:
CODE:
plt.figure(figsize=(8, 6))
plt.scatter(df['Population'], df['Density'],
c='blue', alpha=0.7)
plt.xlabel('Population (Millions)')
plt.ylabel('Density (per 10,000 sq km)')
plt.title('Population vs. Density')
plt.grid(True)
plt.show()

Additional Considerations:
 Error handling:
Incorporate error handling mechanisms (e.g., try-except blocks)
to gracefully handle potential issues during data loading,
manipulation, and visualization.

 Customization:
Explore the extensive customization options available in Matplotlib
and other visualization libraries to tailor plots to your specific
requirements and preferences.

 Scalability:
If you're working with large datasets, consider using optimized data
structures (e.g., NumPy arrays) and efficient algorithms (e.g.,
vectorized operations) for better performance.

 Integration:
Seamlessly integrate NumPy for advanced numerical computations
and array manipulations, and leverage Pandas' powerful data
analysis and manipulation capabilities within your analysis
workflows.

Further Exploration:
Use Pandas' powerful data manipulation functions for complex
operations like merging, grouping, and aggregation.
Explore Matplotlib's various chart types and customization options to
create more sophisticated visualizations.
Integrate NumPy for advanced numerical computations and array
manipulations if needed for your specific analysis.

You might also like