-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcleaning_data.py
More file actions
110 lines (52 loc) · 2.41 KB
/
cleaning_data.py
File metadata and controls
110 lines (52 loc) · 2.41 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# -*- coding: utf-8 -*-
# Examples of cleaning data methods in Python and some introduction into preprocessing
# Libraries
import numpy as np
import pandas as pd
# And also sklearn
# Reading data to DataFrame ===================================================
dataFrame = pd.read_csv("MyData")
# Detecting missing data ======================================================
pd.isnull(dataFrame)
# Replacing specific data into new one
dataFrame.replace(to_replace="New_value", value="Old_value")
# Removing all missing data
dataFrame.dropna()
# Removing missing data from specific columns
dataFrame.dropna(subset=['Column_1'])
# Interpolating data by placing mean values
from sklearn.preprocessing import Imputer
imput = Imputer(missing_values='NaN', strategy='mean', axis=0)
imput = imput.fit(dataFrame)
imputedData = imput.transform(dataFrame.values)
# Dealing with outliers =======================================================
# Get the 98th and 2nd percentile as the limits of our outliers
upperBoundary = np.percentile(dataFrame.values, 98)
lowerBoundary = np.percentile(dataFrame.values, 2)
# Filter the outliers from the dataframe
AnotherDataFrame["ColName"].loc[dataFrame["ColName"]>upperBoundary] = upperBoundary
AnotherDataFrame["ColName"].loc[dataFrame["ColName"]<lowerBoundary] = lowerBoundary
# Handling with categorical data ==============================================
# Unificate names of categorical data
# Whole string lower case
[i.lower() for i in dataFrame["ColName"]]
# First letter capitalised
[i.Capitalize() for i in dataFrame["ColName"]]
# Convert categorical data into integers
from sklearn.preprocessing import LabelEncoder
target_feature = 'Some feature name'
# Using encoder and transform
encoder = LabelEncoder()
enc_Values = encoder.fit_transform(dataFrame[target_feature].values)
dataFrame[target_feature] = pd.Series(enc_Values, index=dataFrame.index)
# Convert categorical data into integers
from sklearn.preprocessing import OneHotEncoder
oneHotEncoder = OneHotEncoder(categorical_features=[0])
dataFrame = oneHotEncoder.fit_transform(dataFrame).toarray()
# Creating dummy features
dataFrame = pd.get_dummies(dataFrame)
# Scaling features ============================================================
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
train_dataFrame= sc.fit_transform(train_dataFrame)
test_dataFrame= sc.transform(test_dataFrame)