0% found this document useful (0 votes)
17 views6 pages

Project 2

The document outlines a project for simulating and analyzing weather data using MySQL and Python. It includes steps for setting up a MySQL database, generating fake temperature data, saving it to the database, and analyzing and plotting the data using Pandas and Matplotlib. Instructions for installing required libraries and running the script are also provided.

Uploaded by

eswarannihil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views6 pages

Project 2

The document outlines a project for simulating and analyzing weather data using MySQL and Python. It includes steps for setting up a MySQL database, generating fake temperature data, saving it to the database, and analyzing and plotting the data using Pandas and Matplotlib. Instructions for installing required libraries and running the script are also provided.

Uploaded by

eswarannihil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Project: Weather Data Simulation and

Analysis

🔧 1. MySQL Table Setup

CREATE DATABASE IF NOT EXISTS


weather_db;

USE weather_db;

CREATE TABLE IF NOT EXISTS daily_weather (


day INT PRIMARY KEY,
temperature FLOAT
);
2. Full Python Code
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import mysql.connector

# 1. Generate fake temperature data using NumPy


np.random.seed(42) # for reproducibility
days = np.arange(1, 31) # 30 days
temperatures = np.random.normal(loc=30,
scale=5, size=30) # mean=30, std=5

# 2. Create DataFrame
df = pd.DataFrame({
'day': days,
'temperature': temperatures
})

# 3. Save to MySQL
try:
conn = mysql.connector.connect(
host="localhost",
user="root",
password="your_password", # Change this!
database="weather_db"
)
cursor = conn.cursor()

cursor.execute("DELETE FROM daily_weather")


conn.commit()

for _, row in df.iterrows():


cursor.execute(
"INSERT INTO daily_weather (day,
temperature) VALUES (%s, %s)",
(int(row['day']), float(row['temperature']))
)
conn.commit()
print("✅ Weather data inserted into MySQL!")

except mysql.connector.Error as err:


print("❌ Error:", err)

finally:
if conn.is_connected():
cursor.close()
conn.close()

# 4. Analyze Data with Pandas


avg_temp = df['temperature'].mean()
max_temp = df['temperature'].max()
min_temp = df['temperature'].min()
print(f"\n📊 Average Temp: {avg_temp:.2f}°C |
Max: {max_temp:.2f}°C | Min: {min_temp:.2f}°C\
n")

# 5. Plot Data using Matplotlib


plt.figure(figsize=(10, 6))
plt.plot(df['day'], df['temperature'], marker='o',
linestyle='-', color='orange')
plt.title("Simulated Daily Temperature Over 30
Days")
plt.xlabel("Day")
plt.ylabel("Temperature (°C)")
plt.grid(True)
plt.tight_layout()
plt.show()

3. Install Required Libraries


pip install numpy pandas matplotlib mysql-
connector-python

▶️4. How to Run


1.Create the weather_db and table in
MySQL.
2.Update the your_password in the code.
3.Run the script:
python weather_analysis.py

You might also like