-
Notifications
You must be signed in to change notification settings - Fork 0
/
clean_data.py
46 lines (34 loc) · 1.48 KB
/
clean_data.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# clean_data.py
from sqlalchemy import create_engine, inspect
import pandas as pd
import os
from dotenv import load_dotenv
load_dotenv()
# Connect to the database
user=os.environ.get("MYSQL_USER")
password=os.environ.get("MYSQL_PASSWORD")
host=os.environ.get("MYSQL_HOST")
database=os.environ.get("MYSQL_DATABASE")
def clean_data():
engine = create_engine(f"mysql+mysqlconnector://{user}:{password}@{host}/{database}")
inspector = inspect(engine)
table_names = inspector.get_table_names()
for table_name in table_names:
df = pd.read_sql_table(table_name, engine)
# Filter out missing values
df = df.dropna()
# Calculate moving average of second column
moving_average = df.iloc[:, 1].rolling(window=10).mean()
# Replace missing values in second column with moving average
df.iloc[:, 1] = df.iloc[:, 1].fillna(moving_average)
# Get IQR for moving average of second column
Q1 = moving_average.quantile(0.05)
Q3 = moving_average.quantile(0.95)
IQR = Q3 - Q1
# Identify and replace outliers in second column with moving average
outliers = df.iloc[:, 1][((df.iloc[:, 1] < (Q1 - 1.5 * IQR)) | (df.iloc[:, 1] > (Q3 + 1.5 * IQR)))]
df.iloc[outliers.index, 1] = moving_average[outliers.index]
# Save cleaned data to table
df.to_sql(table_name, engine, if_exists='replace')
if __name__ == "__main__":
clean_data()