Data Science
Data Science
DATA SCIENCE
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
CERTIFICATE
This is to certify that the work done with respect to, “Data Science” is
bonafide work of Sadiya Shaikh bearing Seat No: 06 submitted in the
requirements for the degree of MASTER OF SCIENCE in
INFORMATION TECHNOLOGY from University of Mumbai.
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
INDEX
Practical
Practical Date Sign
No
1. Creating Data Model using Cassandra.
2. Conversion from different formats to HOURS format.
a Text delimited csv format.
b XML
c JSON
d MySQL DataBase
e Picure(JPEG)
f Video
g Audio
3. Utilities and Auditing
4. Retrieving Data
5. Assessing Data
6. Processing Data
7. Transforming Data
8. Organizing Data
9. Generating Reports
10. Data Visualization with Power BI
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Practical 1
Aim: Creating Data Model using Cassandra
Steps:
Go to Cassandra directory
C:\apache-cassandra-3.11.4\bin
Create table dept ( dept_id int PRIMARY KEY, dept_name text, dept_loc text);
Create table emp ( emp_id int PRIMARY KEY, emp_name text, dept_id int, email text, phone text );
Insert into dept (dept_id, dept_name, dept_loc) values (1001, 'Accounts', 'Mumbai');
Insert into dept (dept_id, dept_name, dept_loc) values (1002, 'Marketing', 'Delhi');
Insert into dept (dept_id, dept_name, dept_loc) values (1003, 'HR', 'Chennai');
Insert into emp ( emp_id, emp_name, dept_id, email, phone ) values (1001, 'ABCD', 1001,
'[email protected]', '1122334455');
Insert into emp ( emp_id, emp_name, dept_id, email, phone ) values (1002, 'DEFG', 1001,
'[email protected]', '2233445566');
Insert into emp ( emp_id, emp_name, dept_id, email, phone ) values (1003, 'GHIJ', 1002,
'[email protected]', '3344556677');
Insert into emp ( emp_id, emp_name, dept_id, email, phone ) values (1004, 'JKLM', 1002,
'[email protected]', '4455667788');
Insert into emp ( emp_id, emp_name, dept_id, email, phone ) values (1005, 'MNOP', 1003,
'[email protected]', '5566778899');
Insert into emp ( emp_id, emp_name, dept_id, email, phone ) values (1006, 'MNOP', 1003,
'[email protected]', '5566778844');
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Prac cal 2a
Aim: Conver ng Text delimited CSV format to HORUS format
Code:
# Utility Start CSV to HORUS =================================
# Standard Tools
#=============================================================
import pandas as pd
# Input Agreement ============================================
sInputFileName='C:/VKHCG/05-DS/9999-Data/Country_Code.csv'
InputData=pd.read_csv(sInputFileName,encoding="latin-1")
print('Input Data Values ===================================')
print(InputData)
print('=====================================================')
# Processing Rules ===========================================
ProcessData=InputData
# Remove columns ISO-2-Code and ISO-3-CODE
ProcessData.drop('ISO-2-CODE', axis=1,inplace=True)
ProcessData.drop('ISO-3-Code', axis=1,inplace=True)
# Rename Country and ISO-M49
ProcessData.rename(columns={'Country': 'CountryName'}, inplace=True)
ProcessData.rename(columns={'ISO-M49': 'CountryNumber'}, inplace=True)
# Set new Index
ProcessData.set_index('CountryNumber', inplace=True)
# Sort data by CurrencyNumber
ProcessData.sort_values('CountryName', axis=0, ascending=False,
inplace=True)
print('Process Data Values =================================')
print(ProcessData)
print('=====================================================')
# Output Agreement ===========================================
OutputData=ProcessData
sOutputFileName='C:/VKHCG/05-DS/9999-Data/HORUS-CSV-Country.csv'
OutputData.to_csv(sOutputFileName, index = False)
print('CSV to HORUS - Done')
# Utility done ===============================================
Output:
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Prac cal 2b
Code:
# Utility Start XML to HORUS =================================
# Standard Tools
import pandas as pd
import xml.etree.ElementTree as ET
def df2xml(data):
header = data.columns
root = ET.Element('root')
for row in range(data.shape[0]):
entry = ET.SubElement(root,'entry')
for index in range(data.shape[1]):
schild=str(header[index])
child = ET.SubElement(entry, schild)
if str(data[schild][row]) != 'nan':
child.text = str(data[schild][row])
else:
child.text = 'n/a'
entry.append(child)
result = ET.tostring(root)
return result
def xml2df(xml_data):
root = ET.XML(xml_data)
all_records = []
for i, child in enumerate(root):
record = {}
for subchild in child:
record[subchild.tag] = subchild.text
all_records.append(record)
return pd.DataFrame(all_records)
sInputFileName='C:/VKHCG/05-DS/9999-Data/Country_Code.xml'
InputData = open(sInputFileName).read()
print('=====================================================')
print('Input Data Values ===================================')
print('=====================================================')
print(InputData)
print('=====================================================')
#=============================================================
# Processing Rules ===========================================
#=============================================================
ProcessDataXML=InputData
# XML to Data Frame
ProcessData=xml2df(ProcessDataXML)
# Remove columns ISO-2-Code and ISO-3-CODE
ProcessData.drop('ISO-2-CODE', axis=1,inplace=True)
ProcessData.drop('ISO-3-Code', axis=1,inplace=True)
# Rename Country and ISO-M49
ProcessData.rename(columns={'Country': 'CountryName'}, inplace=True)
ProcessData.rename(columns={'ISO-M49': 'CountryNumber'}, inplace=True)
# Set new Index
ProcessData.set_index('CountryNumber', inplace=True)
# Sort data by CurrencyNumber
ProcessData.sort_values('CountryName', axis=0, ascending=False,
inplace=True)
print('=====================================================')
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Prac cal 2c
Code:
# Standard Tools
#=============================================================
import pandas as pd
sInputFileName='C:/VKHCG/05-DS/9999-Data/Country_Code.json'
print(InputData)
print('=====================================================')
ProcessData=InputData
ProcessData.drop('ISO-2-CODE', axis=1,inplace=True)
ProcessData.drop('ISO-3-Code', axis=1,inplace=True)
ProcessData.set_index('CountryNumber', inplace=True)
print(ProcessData)
print('=====================================================')
OutputData=ProcessData
sOutputFileName='c:/VKHCG/05-DS/9999-Data/HORUS-JSON-Country.csv'
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Output:
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Prac cal 2d
Aim: Conver ng Database to HORUS format
Code:
# Utility Start Database to HORUS =================================
# Standard Tools
#=============================================================
import pandas as pd
import sqlite3 as sq
# Input Agreement ============================================
sInputFileName='C:/VKHCG/05-DS/9999-Data/utility.db'
sInputTable='Country_Code'
conn = sq.connect(sInputFileName)
sSQL='select * FROM ' + sInputTable + ';'
InputData=pd.read_sql_query(sSQL, conn)
print('Input Data Values ===================================')
print(InputData)
print('=====================================================')
# Processing Rules ===========================================
ProcessData=InputData
# Remove columns ISO-2-Code and ISO-3-CODE
ProcessData.drop('ISO-2-CODE', axis=1,inplace=True)
ProcessData.drop('ISO-3-Code', axis=1,inplace=True)
# Rename Country and ISO-M49
ProcessData.rename(columns={'Country': 'CountryName'}, inplace=True)
ProcessData.rename(columns={'ISO-M49': 'CountryNumber'}, inplace=True)
# Set new Index
ProcessData.set_index('CountryNumber', inplace=True)
# Sort data by CurrencyNumber
ProcessData.sort_values('CountryName', axis=0, ascending=False,
inplace=True)
print('Process Data Values =================================')
print(ProcessData)
print('=====================================================')
# Output Agreement ===========================================
OutputData=ProcessData
sOutputFileName='C:/VKHCG/05-DS/9999-Data/HORUS-CSV-Country.csv'
OutputData.to_csv(sOutputFileName, index = False)
print('Database to HORUS - Done')
# Utility done ===============================================
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Output:
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Prac cal 2e
Aim : Conver ng Image into HORUS format
Code:
import pandas as pd
import numpy as np
# Input Agreement
sInputFileName='C:/VKHCG/05-DS/9999-Data/Angus.jpg'
plt.imshow(InputData)
InputData. shape
print('X: ',InputData.shape[0])
ProcessRawData=InputData.fla en()
y=InputData.shape[2] + 2
x=int(ProcessRawData.shape[0]/y)
ProcessRawData
ProcessData.columns=sColumns
ProcessData
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
print('Rows: ',ProcessData.shape[0])
print('Columns :',ProcessData.shape[1])
OutputData = ProcessData
Output:
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Prac cal 2g
Aim: Conver ng Audio format to HORUS format
Code:
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
#=============================================================
sInputFileName='C:/VKHCG/05-DS/9999-Data/4ch-sound.wav'
print('=====================================================')
print('Processing : ', sInputFileName)
print('=====================================================')
InputRate, InputData = wavfile.read(sInputFileName)
show_info("4 channel", InputData,InputRate)
ProcessData=pd.DataFrame(InputData)
sColumns= ['Ch1','Ch2','Ch3', 'Ch4']
ProcessData.columns=sColumns
OutputData=ProcessData
sOutputFileName='C:/VKHCG/05-DS/9999-Data/HORUS-Audio-4ch.csv'
OutputData.to_csv(sOutputFileName, index = False)
#=============================================================
sInputFileName='C:/VKHCG/05-DS/9999-Data/6ch-sound.wav'
print('=====================================================')
print('Processing : ', sInputFileName)
print('=====================================================')
InputRate, InputData = wavfile.read(sInputFileName)
show_info("6 channel", InputData,InputRate)
ProcessData=pd.DataFrame(InputData)
sColumns= ['Ch1','Ch2','Ch3', 'Ch4', 'Ch5','Ch6']
ProcessData.columns=sColumns
OutputData=ProcessData
sOutputFileName='C:/VKHCG/05-DS/9999-Data/HORUS-Audio-6ch.csv'
OutputData.to_csv(sOutputFileName, index = False)
#=============================================================
sInputFileName='C:/VKHCG/05-DS/9999-Data/8ch-sound.wav'
print('=====================================================')
print('Processing : ', sInputFileName)
print('=====================================================')
InputRate, InputData = wavfile.read(sInputFileName)
show_info("8 channel", InputData,InputRate)
ProcessData=pd.DataFrame(InputData)
sColumns= ['Ch1','Ch2','Ch3', 'Ch4', 'Ch5','Ch6','Ch7','Ch8']
ProcessData.columns=sColumns
OutputData=ProcessData
sOutputFileName='C:/VKHCG/05-DS/9999-Data/HORUS-Audio-8ch.csv'
OutputData.to_csv(sOutputFileName, index = False)
print('=====================================================')
print('Audio to HORUS - Done')
print('=====================================================')
#=============================================================
# U lity done ===============================================
#=============================================================
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Output:
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Prac cal 3a
Aim : Fixer U li es that enable your solu on to take exis ng data and fix a specific quan ty issue.
Code:
baddata = " Data Science with too many spaces is bad!!! "
print('>',baddata,'<')
cleandata=baddata.strip()
print('>',cleandata,'<')
Output:
Code:
import string
printable = set(string.printable)
cleandata=''.join(filter(lambda x: x in string.printable,baddata))
Output:
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Code:
import date me
baddata=format(baddate,'%Y-%m-%d')
gooddata=format(gooddate,'%d %B %Y')
Output:
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Prac cal 3b
Aim : Data binning or bucke ng
Binning is a data preprocessing technique used to reduce the effects of minor observa on errors.
Code:
import numpy as np
np.random.seed(0)
# example data
mu = 90 # mean of distribu on
x = mu + sigma * np.random.randn(5000)
num_bins = 25
fig, ax = plt.subplots()
ax.plot(bins, y, '--')
ax.set_xlabel('Example Data')
ax.set_ylabel('Probability density')
sTitle=r'Histogram ' + str(len(x)) + ' entries into ' + str(num_bins) + ' Bins: $\mu=' + str(mu) +
'$,$\sigma=' +str(sigma) + '$'
ax.set_ tle(sTitle)
fig. ght_layout()
sPathFig='C:/VKHCG/05-DS/4000-UL/0200-DU/DU-Histogram.png'
fig.savefig(sPathFig)
plt.show()
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Output:
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Prac cal 3c
Aim : Averaging of Data
Code:
import pandas as pd
################################################################
InputFileName='IP_DATA_CORE.csv'
OutputFileName='Retrieve_Router_Loca on.csv'
Base='C:/VKHCG'
print('################################')
print('################################')
print('Loading :',sFileName)
IP_DATA_ALL=pd.read_csv(sFileName,header=0,low_memory=False,usecols=['Country','Place
Name','La tude','Longitude'], encoding="la n-1")
print(AllData)
print(MeanData)
################################################################
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Output:
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Prac cal 3d
Aim : Outlier detec on. The data that is different from other data in the set and can cause error in
the data source is removed using outlier detec on
Code:
# Standard Tools
#=============================================================
import pandas as pd
import sqlite3 as sq
sInputFileName='C:/VKHCG/05-DS/9999-Data/u lity.db'
sInputTable='Country_Code'
conn = sq.connect(sInputFileName)
InputData=pd.read_sql_query(sSQL, conn)
print(InputData)
print('=====================================================')
ProcessData=InputData
ProcessData.drop('ISO-2-CODE', axis=1,inplace=True)
ProcessData.drop('ISO-3-Code', axis=1,inplace=True)
ProcessData.set_index('CountryNumber', inplace=True)
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
print(ProcessData)
print('=====================================================')
OutputData=ProcessData
sOutputFileName='C:/VKHCG/05-DS/9999-Data/HORUS-CSV-Country.csv'
Output:
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Prac cal 4a
Aim : Program to retrieve and perform data processing using R
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Prac cal 4b
Aim : Program to retrieve different a ributes of data.
Code :
##############Retrieve-IP_DATA_ALL.py########################
# -*- coding: utf-8 -*-
################################################################
import sys
import os
import pandas as pd
################################################################
Base='C:/VKHCG'
################################################################
sFileName=Base + '/01-Vermeulen/00-RawData/IP_DATA_ALL.csv'
print('Loading :',sFileName)
IP_DATA_ALL=pd.read_csv(sFileName,header=0,low_memory=False,
encoding="latin-1")
################################################################
sFileDir=Base + '/01-Vermeulen/01-Retrieve/01-EDS/02-Python'
if not os.path.exists(sFileDir):
os.makedirs(sFileDir)
print('Rows:', IP_DATA_ALL.shape[0])
print('Columns:', IP_DATA_ALL.shape[1])
print('### Raw Data Set #####################################')
for i in range(0,len(IP_DATA_ALL.columns)):
print(IP_DATA_ALL.columns[i],type(IP_DATA_ALL.columns[i]))
print('### Fixed Data Set ###################################')
IP_DATA_ALL_FIX=IP_DATA_ALL
for i in range(0,len(IP_DATA_ALL.columns)):
cNameOld=IP_DATA_ALL_FIX.columns[i] + ' '
cNameNew=cNameOld.strip().replace(" ", ".")
IP_DATA_ALL_FIX.columns.values[i] = cNameNew
print(IP_DATA_ALL.columns[i],type(IP_DATA_ALL.columns[i]))
################################################################
#print(IP_DATA_ALL_FIX.head())
################################################################
print('Fixed Data Set with ID')
IP_DATA_ALL_with_ID=IP_DATA_ALL_FIX
IP_DATA_ALL_with_ID.index.names = ['RowID']
#print(IP_DATA_ALL_with_ID.head())
sFileName2=sFileDir + '/Retrieve_IP_DATA.csv'
IP_DATA_ALL_with_ID.to_csv(sFileName2, index = True, encoding="latin-
1")
################################################################
print('### Done!! ############################################')
################################################################
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Output :
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Prac cal 4c
Aim : Crea ng a Data Pa ern by taking a string input and crea ng a pa ern of uppercase and
lowercase alterna vely in the string.
Code :
import pandas as pd
res = ""
if not idx % 2:
else:
# prin ng result
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Output :
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Prac cal 4d
Code :
import sys
import os
import pandas as pd
################################################################
Base='C:/VKHCG'
################################################################
sFileName=Base + '/01-Vermeulen/00-RawData/Created_data.csv'
print('Loading :',sFileName)
################################################################
sFileDir=Base + '/01-Vermeulen/01-Retrieve/01-EDS/02-Python'
if not os.path.exists(sFileDir):
os.makedirs(sFileDir)
print('Rows:', IP_DATA_ALL.shape[0])
print('Columns:', IP_DATA_ALL.shape[1])
for i in range(0,len(IP_DATA_ALL.columns)):
print(IP_DATA_ALL.columns[i],type(IP_DATA_ALL.columns[i]))
IP_DATA_ALL_FIX=IP_DATA_ALL
for i in range(0,len(IP_DATA_ALL.columns)):
IP_DATA_ALL_FIX.columns.values[i] = cNameNew
print(IP_DATA_ALL.columns[i],type(IP_DATA_ALL.columns[i]))
################################################################
#print(IP_DATA_ALL_FIX.head())
################################################################
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
IP_DATA_ALL_with_ID=IP_DATA_ALL_FIX
IP_DATA_ALL_with_ID.index.names = ['RowID']
#print(IP_DATA_ALL_with_ID.head())
sFileName2=sFileDir + '/Retrieve_IP_DATA.csv'
################################################################
################################################################
Output :
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Practical 5a
Assessing Data
Aim: Perform error management on the given data using pandas package.
Code:
################### Assess-Good-Bad-01.py########################
# -*- coding: utf-8 -*- ################################################################
import sys
import os
import pandas as pd
################################################################
Base='C:/VKHCG'
################################################################
print('################################')
print('Working Base :',Base, ' using ', sys.platform)
print('################################')
################################################################
sInputFileName='Good-or-Bad.csv'
sOutputFileName='Good-or-Bad-01.csv'
Company='01-Vermeulen'
################################################################
Base='C:/VKHCG'
################################################################
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Output:
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
All of column E has been deleted, owing to the fact that all values in that column were missing
values/errors.
ii. Drop the Columns Where Any of the Elements Is Missing Values
################## Assess-Good-Bad-02.py########################### # -*-
coding: utf-8 -*-
################################################################
import sys
import os
import pandas as pd
################################################################
Base='C:/VKHCG'
sInputFileName='Good-or-Bad.csv'
sOutputFileName='Good-or-Bad-02.csv'
Company='01-Vermeulen'
################################################################
Base='C:/VKHCG'
################################################################
print('################################')
print('Working Base :',Base, ' using ', sys.platform)
print('################################')
################################################################
sFileDir=Base + '/' + Company + '/02-Assess/01-EDS/02-Python'
if not os.path.exists(sFileDir):
os.makedirs(sFileDir)
################################################################
###
Import Warehouse ################################################################
sFileName=Base + '/' + Company + '/00-RawData/' + sInputFileName print('Loading :',sFileName)
RawData=pd.read_csv(sFileName,header=0)
print('################################')
print('## Raw Data Values')
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
print('################################')
print(RawData)
print('################################')
print('## Data Profile')
print('################################')
print('Rows :',RawData.shape[0])
print('Columns :',RawData.shape[1])
print('################################')
################################################################
sFileName=sFileDir + '/' + sInputFileName RawData.to_csv(sFileName, index = False)
################################################################
TestData=RawData.dropna(axis=1, how='any')
################################################################
print('################################')
print('## Test Data Values')
print('################################')
print(TestData)
print('################################')
print('## Data Profile')
print('################################')
print('Rows :',TestData.shape[0]) print('Columns :',TestData.shape[1])
print('################################')
################################################################
sFileName=sFileDir + '/' + sOutputFileName TestData.to_csv(sFileName, index = False)
################################################################
print('################################')
print('### Done!! #####################')
print('################################')
################################################################
Output:
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
iii. Keep Only the Rows That Contain a Maximum of Two Missing Values
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
print('################################')
print('## Raw Data Values')
print('################################')
print(RawData)
print('################################')
print('## Data Profile')
print('################################')
print('Rows :',RawData.shape[0])
print('Columns :',RawData.shape[1])
print('################################')
################################################################
sFileName=sFileDir + '/' + sInputFileName RawData.to_csv(sFileName, index = False)
################################################################
TestData=RawData.dropna(thresh=2)
print('################################')
print('## Test Data Values')
print('################################')
print(TestData)
print('################################')
print('## Data Profile')
print('################################')
print('Rows :',TestData.shape[0])
print('Columns :',TestData.shape[1])
print('################################')
sFileName=sFileDir + '/' + sOutputFileName
TestData.to_csv(sFileName, index = False)
################################################################
print('################################')
print('### Done!! #####################')
print('################################')
################################################################
Output:
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
The next step along the route is to generate a full network routing solution for the company, to resolve
the data issues in the retrieve data.
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Practical 5b
Aim: Write Python / R program to create the network routing diagram from the given data on routers.
########## Assess-Network-Routing-Company.py #####################
import sys
import os
import pandas as pd
################################################################
pd.options.mode.chained_assignment = None
################################################################
Base='C:/VKHCG'
################################################################
print('################################')
print('Working Base :',Base, ' using Windows')
print('################################')
################################################################
sInputFileName1='01-Retrieve/01-EDS/01-R/Retrieve_Country_Code.csv'
sInputFileName2='01-Retrieve/01-EDS/02-Python/Retrieve_Router_Location.csv'
sInputFileName3='01-Retrieve/01-EDS/01-R/Retrieve_IP_DATA.csv'
################################################################
sOutputFileName='Assess-Network-Routing-Company.csv' Company='01-Vermeulen'
################################################################
################################################################
### Import Country Data
################################################################
sFileName=Base + '/' + Company + '/' + sInputFileName1
print('################################')
print('Loading :',sFileName)
print('################################')
CountryData=pd.read_csv(sFileName,header=0,low_memory=False, encoding="latin-1")
print('Loaded Country:',CountryData.columns.values)
print('################################')
################################################################
## Assess Country Data
################################################################
print('################################')
print('Changed :',CountryData.columns.values)
CountryData.rename(columns={'Country': 'Country_Name'}, inplace=True)
CountryData.rename(columns={'ISO-2-CODE': 'Country_Code'}, inplace=True)
CountryData.drop('ISO-M49', axis=1, inplace=True)
CountryData.drop('ISO-3-Code', axis=1, inplace=True) CountryData.drop('RowID', axis=1,
inplace=True)
print('To :',CountryData.columns.values)
print('################################')
################################################################
################################################################
### Import Company Data
################################################################
sFileName=Base + '/' + Company + '/' + sInputFileName2
print('################################')
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
print('Loading :',sFileName)
print('################################')
CompanyData=pd.read_csv(sFileName,header=0,low_memory=False, encoding="latin-1")
print('Loaded Company :',CompanyData.columns.values)
print('################################')
################################################################
## Assess Company Data
################################################################
print('################################')
print('Changed :',CompanyData.columns.values)
CompanyData.rename(columns={'Country': 'Country_Code'}, inplace=True)
print('To :',CompanyData.columns.values)
print('################################')
################################################################
################################################################
### Import Customer Data
################################################################
sFileName=Base + '/' + Company + '/' + sInputFileName3
print('################################')
print('Loading :',sFileName)
print('################################')
CustomerRawData=pd.read_csv(sFileName,header=0,low_memory=False, encoding="latin-1")
print('################################')
print('Loaded Customer :',CustomerRawData.columns.values)
print('################################')
################################################################
CustomerData=CustomerRawData.dropna(axis=0, how='any')
print('################################')
print('Remove Blank Country Code')
print('Reduce Rows from', CustomerRawData.shape[0],' to ', CustomerData.shape[0])
print('################################')
################################################################
print('################################')
print('Changed :',CustomerData.columns.values) CustomerData.rename(columns={'Country':
'Country_Code'}, inplace=True)
print('To :',CustomerData.columns.values) print('################################')
################################################################
print('################################')
print('Merge Company and Country Data')
print('################################')
CompanyNetworkData=pd.merge(
CompanyData,
CountryData,
how='inner',
on='Country_Code'
)
################################################################
print('################################')
print('Change ',CompanyNetworkData.columns.values)
for i in CompanyNetworkData.columns.values:
j='Company_'+i
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Output:
Go to C:\VKHCG\01-Vermeulen\02-Assess\01-EDS\02-Python folder and open Assess-Network-
Routing-Company.csv
Next, Access the the customers location using network router location.
####################Assess-Network-Routing-Customer.py ######################
import sys
import os
import pandas as pd ################################################################
pd.options.mode.chained_assignment = None
################################################################
Base='C:/VKHCG'
print('################################')
print('Working Base :',Base, ' using ', sys.platform)
print('################################')
################################################################
sInputFileName=Base+'/01-Vermeulen/02-Assess/01-EDS/02-Python/Assess-Network-Routing-
Customer.csv'
################################################################
sOutputFileName='Assess-Network-Routing-Customer.gml'
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Company='01-Vermeulen'
################################################################
### Import Country Data
################################################################
sFileName=sInputFileName
print('################################')
print('Loading :',sFileName)
print('################################')
CustomerData=pd.read_csv(sFileName,header=0,low_memory=False, encoding="latin-1")
print('Loaded Country:',CustomerData.columns.values)
print('################################')
print(CustomerData.head())
print('################################')
print('### Done!! #####################')
print('################################')
################################################################
Output
Assess-Network-Routing-Customer.csv
Assess-Network-Routing-Node.py
################################################################
import sys
import os
import pandas as pd ################################################################
pd.options.mode.chained_assignment = None
################################################################
Base='C:/VKHCG'
################################################################
print('################################')
print('Working Base :',Base, ' using ', sys.platform)
print('################################')
################################################################
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
sInputFileName='01-Retrieve/01-EDS/02-Python/Retrieve_IP_DATA.csv'
################################################################
sOutputFileName='Assess-Network-Routing-Node.csv' Company='01-Vermeulen'
################################################################
###
Import IP Data ################################################################
sFileName=Base + '/' + Company + '/' + sInputFileName
print('################################')
print('Loading :',sFileName)
print('################################')
IPData=pd.read_csv(sFileName,header=0,low_memory=False, encoding="latin-1")
print('Loaded IP :', IPData.columns.values)
print('################################')
################################################################
print('################################')
print('Changed :',IPData.columns.values) IPData.drop('RowID', axis=1, inplace=True)
IPData.drop('ID', axis=1, inplace=True)
IPData.rename(columns={'Country': 'Country_Code'}, inplace=True)
IPData.rename(columns={'Place.Name': 'Place_Name'}, inplace=True)
IPData.rename(columns={'Post.Code': 'Post_Code'}, inplace=True)
IPData.rename(columns={'First.IP.Number': 'First_IP_Number'}, inplace=True)
IPData.rename(columns={'Last.IP.Number': 'Last_IP_Number'}, inplace=True)
print('To :',IPData.columns.values)
print('################################')
################################################################
print('################################')
print('Change ',IPData.columns.values)
for i in IPData.columns.values:
j='Node_'+i
IPData.rename(columns={i: j}, inplace=True)
print('To ', IPData.columns.values)
sFileDir=Base + '/' + Company + '/02-Assess/01-EDS/02-Python'
if not os.path.exists(sFileDir):
os.makedirs(sFileDir)
################################################################
sFileName=sFileDir + '/' + sOutputFileName
print('################################')
print('Storing :', sFileName)
print('################################')
IPData.to_csv(sFileName, index = False, encoding="latin-1")
################################################################
print('################################')
print('### Done!! #####################')
print('################################')
################################################################
print('################################')
Output:
C:/VKHCG/01-Vermeulen/02-Assess/01-EDS/02-Python/Assess-Network-Routing-Node.csv
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Practical 5c
Aim: Write a Python / R program to build directed acyclic graph.
Code:
Open your python editor and create a file named Assess-DAG-Location.py in directory
C:\VKHCG\01-Vermeulen\02-Assess
################################################################
import networkx as nx
import matplotlib.pyplot as plt
import sys
import os
import pandas as pd
################################################################
Base='C:/VKHCG'
################################################################
print('################################')
print('Working Base :',Base, ' using ', sys.platform)
print('################################')
################################################################
sInputFileName='01-Retrieve/01-EDS/02-Python/Retrieve_Router_Location.csv'
sOutputFileName1='Assess-DAG-Company-Country.png'
sOutputFileName2='Assess-DAG-Company-Country-Place.png'
Company='01-Vermeulen'
################################################################
### Import Company Data
################################################################
sFileName=Base + '/' + Company + '/' + sInputFileName
print('################################')
print('Loading :',sFileName)
print('################################')
CompanyData=pd.read_csv(sFileName,header=0,low_memory=False, encoding="latin-1")
print('Loaded Company :',CompanyData.columns.values)
print('################################')
################################################################
print(CompanyData)
print('################################')
print('Rows : ',CompanyData.shape[0])
print('################################')
################################################################
G1=nx.DiGraph() G2=nx.DiGraph()
################################################################
for i in range(CompanyData.shape[0]):
G1.add_node(CompanyData['Country'][i])
sPlaceName= CompanyData['Place_Name'][i] + '-' + CompanyData['Country'][i]
G2.add_node(sPlaceName)
print('################################')
for n1 in G1.nodes():
for n2 in G1.nodes():
if n1 != n2:
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
print('################################')
print("Nodes of graph: ")
print(G1.nodes())
print("Edges of graph: ")
print(G1.edges())
print('################################')
################################################################
sFileDir=Base + '/' + Company + '/02-Assess/01-EDS/02-Python'
if not os.path.exists(sFileDir):
os.makedirs(sFileDir)
################################################################
sFileName=sFileDir + '/' + sOutputFileName1
print('################################')
print('Storing :', sFileName)
print('################################')
nx.draw(G1,pos=nx.spectral_layout(G1),
nodecolor='r',edge_color='g',
with_labels=True,node_size=8000,
font_size=12)
plt.savefig(sFileName) # save as png
plt.show() # display
################################################################
print('################################')
for n1 in G2.nodes():
for n2 in G2.nodes():
if n1 != n2:
print('Link :',n1,' to ', n2)
G2.add_edge(n1,n2)
print('################################')
print('################################')
print("Nodes of graph: ")
print(G2.nodes())
print("Edges of graph: ")
print(G2.edges())
print('################################')
################################################################
sFileDir=Base + '/' + Company + '/02-Assess/01-EDS/02-Python'
if not os.path.exists(sFileDir):
os.makedirs(sFileDir)
################################################################
sFileName=sFileDir + '/' + sOutputFileName2
print('################################')
print('Storing :', sFileName)
print('################################')
nx.draw(G2,pos=nx.spectral_layout(G2),
nodecolor='r',edge_color='b',
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
with_labels=True,node_size=8000,
font_size=12)
plt.savefig(sFileName) # save as png
plt.show() # display
################################################################
Output:
################################
Rows : 150 ################################ ################################
Link : US to DE
Link : US to GB
Link : DE to US
Link : DE to GB
Link : GB to US
Link : GB to DE
################################ ################################
Nodes of graph:
['US', 'DE', 'GB']
Edges of graph:
[('US', 'DE'), ('US', 'GB'), ('DE', 'US'), ('DE', 'GB'), ('GB', 'US'), ('GB', 'DE')]
################################
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
print('################################')
################################################################
sInputFileName='01-Retrieve/01-EDS/02-Python/Retrieve_Router_Location.csv'
sOutputFileName1='Assess-DAG-Company-Country.png'
sOutputFileName2='Assess-DAG-Company-Country-Place.png'
Company='01-Vermeulen'
################################################################
### Import Company Data
################################################################
sFileName=Base + '/' + Company + '/' + sInputFileName
print('################################')
print('Loading :',sFileName)
print('################################')
CompanyData=pd.read_csv(sFileName,header=0,low_memory=False, encoding="latin-1")
print('Loaded Company :',CompanyData.columns.values)
print('################################')
################################################################
print(CompanyData)
print('################################')
print('Rows : ',CompanyData.shape[0])
print('################################')
################################################################
G1=nx.DiGraph() G2=nx.DiGraph()
################################################################
for i in range(CompanyData.shape[0]):
G1.add_node(CompanyData['Country'][i])
sPlaceName= CompanyData['Place_Name'][i] + '-' + CompanyData['Country'][i]
G2.add_node(sPlaceName)
print('################################')
for n1 in G1.nodes():
for n2 in G1.nodes():
if n1 != n2:
print('Link :',n1,' to ', n2)
G1.add_edge(n1,n2)
print('################################')
print('################################')
print("Nodes of graph: ")
print(G1.nodes())
print("Edges of graph: ")
print(G1.edges())
print('################################')
################################################################
sFileDir=Base + '/' + Company + '/02-Assess/01-EDS/02-Python'
if not os.path.exists(sFileDir):
os.makedirs(sFileDir)
################################################################
sFileName=sFileDir + '/' + sOutputFileName1
print('################################')
print('Storing :', sFileName)
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
print('################################')
nx.draw(G1,pos=nx.spectral_layout(G1),
nodecolor='r',edge_color='g',
with_labels=True,node_size=8000,
font_size=12)
plt.savefig(sFileName) # save as png
plt.show() # display
################################################################
print('################################')
for n1 in G2.nodes():
for n2 in G2.nodes():
if n1 != n2:
print('Link :',n1,' to ', n2)
G2.add_edge(n1,n2)
print('################################')
print('################################')
print("Nodes of graph: ")
print(G2.nodes())
print("Edges of graph: ")
print(G2.edges())
print('################################')
################################################################
sFileDir=Base + '/' + Company + '/02-Assess/01-EDS/02-Python' if not os.path.exists(sFileDir):
os.makedirs(sFileDir) ################################################################
sFileName=sFileDir + '/' + sOutputFileName2
print('################################')
print('Storing :', sFileName)
print('################################')
nx.draw(G2,pos=nx.spectral_layout(G2),
nodecolor='r',edge_color='b',
with_labels=True,node_size=8000,
font_size=12)
plt.savefig(sFileName) # save as png
plt.show() # display
################################################################
Output:
################################
Link : New York-US to Munich-DE
Link : New York-US to London-GB
Link : Munich-DE to New York-US
Link : Munich-DE to London-GB
Link : London-GB to New York-US
Link : London-GB to Munich-DE
################################ ################################
Nodes of graph:
['New York-US', 'Munich-DE', 'London-GB'] Edges of graph:
[('New York-US', 'Munich-DE'), ('New York-US', 'London-GB'), ('Munich-DE', 'New York-US'),
('Munich-DE', 'London-GB'), ('London-GB', 'New York-US'), ('London-GB', 'Munich-DE')]
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Open your Python editor and create a file named Assess-DAG-GPS.py in directory C:\VKHCG\01-
Vermeulen\02-Assess.
import networkx as nx
import matplotlib.pyplot as plt
import sys
import os
import pandas as pd
Base='C:/VKHCG'
print('################################')
print('Working Base :',Base, ' using ', sys.platform)
print('################################')
sInputFileName='01-Retrieve/01-EDS/02-Python/Retrieve_Router_Location.csv'
sOutputFileName='Assess-DAG-Company-GPS.png'
Company='01-Vermeulen'
### Import Company Data
sFileName=Base + '/' + Company + '/' + sInputFileName
print('################################')
print('Loading :',sFileName)
print('################################')
CompanyData=pd.read_csv(sFileName,header=0,low_memory=False, encoding="latin-1")
print('Loaded Company :',CompanyData.columns.values)
print('################################')
print(CompanyData)
print('################################')
print('Rows : ',CompanyData.shape[0])
print('################################')
G=nx.Graph()
for i in range(CompanyData.shape[0]):
nLatitude=round(CompanyData['Latitude'][i],2)
nLongitude=round(CompanyData['Longitude'][i],2)
if nLatitude < 0:
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
if nLongitude < 0:
sLongitude = str(nLongitude*-1) + ' W'
else:
sLongitude = str(nLongitude) + ' E'
print('################################')
for n1 in G.nodes():
for n2 in G.nodes():
if n1 != n2:
print('Link :',n1,' to ', n2)
G.add_edge(n1,n2)
print('################################')
print('################################')
print("Nodes of graph: ")
print(G.number_of_nodes())
print("Edges of graph: ")
print(G.number_of_edges())
print('################################')
Output:
=== RESTART: C:\VKHCG\01-Vermeulen\02-Assess\Assess-DAG-GPS-unsmoothed.py ===
################################
Working Base : C:/VKHCG using win32
################################
Loading : C:/VKHCG/01-Vermeulen/01-Retrieve/01-EDS/02-Python/Retrieve_Router_Location.csv
################################
Loaded Company : ['Country' 'Place_Name' 'Latitude' 'Longitude']
################################
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Practical 5d
Aim: Write a Python / R program to pick the content for Bill Boards from the given data.
Picking Content for Billboards
The basic process required is to combine two sets of data and then calculate the number of visitors per
day from the range of IP addresses that access the billboards in Germany.
Bill Board Location: Rows - 8873
Access Visitors: Rows - 75999
Access Location Record: Rows – 1,81,235
Open Python editor and create a file named Assess-DE-Billboard.py in directory C:\VKHCG\02-
Krennwallner\02-Assess
################# Assess-DE-Billboard.py######################
import sys
import os
import sqlite3 as sq
import pandas as pd
################################################################
Base='C:/VKHCG'
print('################################')
print('Working Base :',Base, ' using ', sys.platform)
print('################################')
################################################################
sInputFileName1='01-Retrieve/01-EDS/02-Python/Retrieve_DE_Billboard_Locations.csv'
sInputFileName2='01-Retrieve/01-EDS/02-Python/Retrieve_Online_Visitor.csv'
sOutputFileName='Assess-DE-Billboard-Visitor.csv'
Company='02-Krennwallner'
################################################################
sDataBaseDir=Base + '/' + Company + '/02-Assess/SQLite'
if not os.path.exists(sDataBaseDir):
os.makedirs(sDataBaseDir)
################################################################
sDatabaseName=sDataBaseDir + '/krennwallner.db'
conn = sq.connect(sDatabaseName)
################################################################
### Import Billboard Data
################################################################
sFileName=Base + '/' + Company + '/' + sInputFileName1
print('################################')
print('Loading :',sFileName)
print('################################')
BillboardRawData=pd.read_csv(sFileName,header=0,low_memory=False, encoding="latin-1")
BillboardRawData.drop_duplicates(subset=None, keep='first', inplace=True)
BillboardData=BillboardRawData
print('Loaded Company :',BillboardData.columns.values)
print('################################')
################################################################
print('################')
sTable='Assess_BillboardData'
print('Storing :',sDatabaseName,' Table:',sTable)
BillboardData.to_sql(sTable, conn, if_exists="replace")
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
print('################')
################################################################
print(BillboardData.head())
print('################################')
print('Rows : ',BillboardData.shape[0])
print('################################')
################################################################
### Import Billboard Data
################################################################
sFileName=Base + '/' + Company + '/' + sInputFileName2
print('################################')
print('Loading :',sFileName)
print('################################')
VisitorRawData=pd.read_csv(sFileName,header=0,low_memory=False, encoding="latin-1")
VisitorRawData.drop_duplicates(subset=None, keep='first', inplace=True)
VisitorData=VisitorRawData[VisitorRawData.Country=='DE']
print('Loaded Company :',VisitorData.columns.values)
print('################################')
################################################################
print('################')
sTable='Assess_VisitorData'
print('Storing :',sDatabaseName,' Table:',sTable)
VisitorData.to_sql(sTable, conn, if_exists="replace")
print('################')
################################################################
print(VisitorData.head())
print('################################')
print('Rows : ',VisitorData.shape[0])
print('################################')
################################################################
print('################')
sTable='Assess_BillboardVisitorData'
print('Loading :',sDatabaseName,' Table:',sTable)
sSQL="select distinct"
sSQL=sSQL+ " A.Country AS BillboardCountry,"
sSQL=sSQL+ " A.Place_Name AS BillboardPlaceName,"
sSQL=sSQL+ " A.Latitude AS BillboardLatitude, "
sSQL=sSQL+ " A.Longitude AS BillboardLongitude,"
sSQL=sSQL+ " B.Country AS VisitorCountry,"
sSQL=sSQL+ " B.Place_Name AS VisitorPlaceName,"
sSQL=sSQL+ " B.Latitude AS VisitorLatitude, "
sSQL=sSQL+ " B.Longitude AS VisitorLongitude,"
sSQL=sSQL+ " (B.Last_IP_Number - B.First_IP_Number) * 365.25 * 24 * 12 AS VisitorYearRate"
sSQL=sSQL+ " from"
sSQL=sSQL+ " Assess_BillboardData as A"
sSQL=sSQL+ " JOIN "
sSQL=sSQL+ " Assess_VisitorData as B"
sSQL=sSQL+ " ON "
sSQL=sSQL+ " A.Country = B.Country"
sSQL=sSQL+ " AND "
sSQL=sSQL+ " A.Place_Name = B.Place_Name;"
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
BillboardVistorsData=pd.read_sql_query(sSQL, conn)
print('################')
################################################################
print('################')
sTable='Assess_BillboardVistorsData'
print('Storing :',sDatabaseName,' Table:',sTable)
BillboardVistorsData.to_sql(sTable, conn, if_exists="replace")
print('################')
################################################################
print(BillboardVistorsData.head())
print('################################')
print('Rows : ',BillboardVistorsData.shape[0])
print('################################')
################################################################
sFileDir=Base + '/' + Company + '/02-Assess/01-EDS/02-Python'
if not os.path.exists(sFileDir):
os.makedirs(sFileDir)
################################################################
print('################################')
print('Storing :', sFileName)
print('################################')
sFileName=sFileDir + '/' + sOutputFileName BillboardVistorsData.to_csv(sFileName, index = False)
print('################################')
################################################################
print('### Done!! ############################################')
################################################################
Output:
C:\VKHCG\02-Krennwallner\01-Retrieve\01-EDS\02-Python\Retrieve_Online_Visitor.csv
containing, 10,48,576(Ten lack Forty Eight Thousand Five Hundred and Seventy Six )rows.
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Table:
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Practical 6
Processing Data
Aim: Build the time hub, links, and satellites.
Code:
Open your Python editor and create a file named Process_Time.py. Save it into directory
C:\VKHCG\01-Vermeulen\03-Process.
################################################################
# -*- coding: utf-8 -*-
################################################################
import sys
import os
from datetime import datetime
from datetime import timedelta
from pytz import timezone, all_timezones
import pandas as pd
import sqlite3 as sq
from pandas.io
import sql
import uuid
pd.options.mode.chained_assignment = None
################################################################
if sys.platform == 'linux':
Base=os.path.expanduser('~') + '/VKHCG'
else:
Base='C:/VKHCG'
print('################################')
print('Working Base :',Base, ' using ', sys.platform)
print('################################')
################################################################
Company='01-Vermeulen'
InputDir='00-RawData'
InputFileName='VehicleData.csv'
################################################################
sDataBaseDir=Base + '/' + Company + '/03-Process/SQLite'
if not os.path.exists(sDataBaseDir):
os.makedirs(sDataBaseDir)
################################################################
sDatabaseName=sDataBaseDir + '/Hillman.db'
conn1 = sq.connect(sDatabaseName)
################################################################
sDataVaultDir=Base + '/88-DV'
if not os.path.exists(sDataBaseDir):
os.makedirs(sDataBaseDir)
################################################################
sDatabaseName=sDataVaultDir + '/datavault.db' conn2 = sq.connect(sDatabaseName)
################################################################
base = datetime(2018,1,1,0,0,0)
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
numUnits=10*365*24
################################################################
date_list = [base - timedelta(hours=x) for x in range(0, numUnits)]
t=0
for i in date_list:
now_utc=i.replace(tzinfo=timezone('UTC'))
sDateTime=now_utc.strftime("%Y-%m-%d %H:%M:%S")
print(sDateTime)
sDateTimeKey=sDateTime.replace(' ','-').replace(':','-') t+=1
IDNumber=str(uuid.uuid4())
TimeLine=[('ZoneBaseKey', ['UTC']),
('IDNumber', [IDNumber]),
('nDateTimeValue', [now_utc]),
('DateTimeValue', [sDateTime]),
('DateTimeKey', [sDateTimeKey])]
if t==1:
TimeFrame = pd.DataFrame.from_items(TimeLine)
else:
TimeRow = pd.DataFrame.from_items(TimeLine)
TimeFrame = TimeFrame.append(TimeRow)
################################################################
TimeHub=TimeFrame[['IDNumber','ZoneBaseKey','DateTimeKey','DateTimeValue']]
TimeHubIndex=TimeHub.set_index(['IDNumber'],inplace=False)
################################################################
TimeFrame.set_index(['IDNumber'],inplace=True)
################################################################
sTable = 'Process-Time'
print('Storing :',sDatabaseName,' Table:',sTable)
TimeHubIndex.to_sql(sTable, conn1, if_exists="replace")
################################################################
sTable = 'Hub-Time'
print('Storing :',sDatabaseName,' Table:',sTable)
TimeHubIndex.to_sql(sTable, conn2, if_exists="replace")
################################################################
active_timezones=all_timezones
z=0
for zone in active_timezones:
t=0
for j in range(TimeFrame.shape[0]):
now_date=TimeFrame['nDateTimeValue'][j]
DateTimeKey=TimeFrame['DateTimeKey'][j]
now_utc=now_date.replace(tzinfo=timezone('UTC'))
sDateTime=now_utc.strftime("%Y-%m-%d %H:%M:%S")
now_zone = now_utc.astimezone(timezone(zone))
sZoneDateTime=now_zone.strftime("%Y-%m-%d %H:%M:%S")
print(sZoneDateTime)
t+=1
z+=1
IDZoneNumber=str(uuid.uuid4())
TimeZoneLine=[('ZoneBaseKey', ['UTC']),
('IDZoneNumber', [IDZoneNumber]),
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
('DateTimeKey', [DateTimeKey]),
('UTCDateTimeValue', [sDateTime]),
('Zone', [zone]),
('DateTimeValue', [sZoneDateTime])]
if t==1:
TimeZoneFrame = pd.DataFrame.from_items(TimeZoneLine)
else:
TimeZoneRow = pd.DataFrame.from_items(TimeZoneLine)
TimeZoneFrame = TimeZoneFrame.append(TimeZoneRow)
TimeZoneFrameIndex=TimeZoneFrame.set_index(['IDZoneNumber'],inplace=False)
sZone=zone.replace('/','-').replace(' ','')
#############################################################
sTable = 'Process-Time-'+sZone
print('Storing :',sDatabaseName,' Table:',sTable)
print('################')
################################################################# print('### Done!!
############################################')
#################################################################
You have built your first hub and satellites for time in the data vault.
The data vault has been built in directory ..\ VKHCG\88-DV\datavault.db. You can access it with your
SQLite tools
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Golden Nominal
A golden nominal record is a single person’s record, with distinctive references for use by all systems.
This gives the system a single view of the person. I use first name, other names, last name, and birth
date as my golden nominal. The data we have in the assess directory requires a birth date to become a
golden nominal. The program will generate a golden nominal using our sample data set.
Open your Python editor and create a file called Process-People.py in the .. C:\VKHCG\04-Clark\03-
Process directory.
################################################################
import sys
import os
import sqlite3 as sq
import pandas as pd
from pandas.io
import sql
from datetime
import datetime, timedelta
from pytz import timezone, all_timezones
from random import randint
import uuid ################################################################
if sys.platform == 'linux':
Base=os.path.expanduser('~') + '/VKHCG'
else:
Base='C:/VKHCG' print('################################')
print('Working Base :',Base, ' using ', sys.platform)
print('################################')
################################################################
Company='04-Clark'
sInputFileName='02-Assess/01-EDS/02-Python/Assess_People.csv'
################################################################
sDataBaseDir=Base + '/' + Company + '/03-Process/SQLite'
if not os.path.exists(sDataBaseDir):
os.makedirs(sDataBaseDir)
################################################################
sDatabaseName=sDataBaseDir + '/clark.db'
conn1 = sq.connect(sDatabaseName)
################################################################
sDataVaultDir=Base + '/88-DV'
if not os.path.exists(sDataBaseDir):
os.makedirs(sDataBaseDir)
################################################################
sDatabaseName=sDataVaultDir + '/datavault.db'
conn2 = sq.connect(sDatabaseName)
################################################################
### Import Female Data
################################################################
sFileName=Base + '/' + Company + '/' + sInputFileName
print('################################')
print('Loading :',sFileName)
print('################################')
print(sFileName)
RawData=pd.read_csv(sFileName,header=0,low_memory=False,encoding="latin-1")
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
start_date = datetime(1900,1,1,0,0,0)
start_date_utc=start_date.replace(tzinfo=timezone('UTC'))
HoursBirth=100*365*24
RawData['BirthDateUTC']=RawData.apply(lambda row:
(start_date_utc + timedelta(hours=randint(0, HoursBirth)))
,axis=1)
zonemax=len(all_timezones)-1
RawData['TimeZone']=RawData.apply(lambda row:
(all_timezones[randint(0, zonemax)])
,axis=1)
RawData['BirthDateISO']=RawData.apply(lambda row:
row["BirthDateUTC"].astimezone(timezone(row['TimeZone']))
,axis=1)
RawData['BirthDateKey']=RawData.apply(lambda row:
row["BirthDateUTC"].strftime("%Y-%m-%d %H:%M:%S")
,axis=1)
RawData['BirthDate']=RawData.apply(lambda row:
row["BirthDateISO"].strftime("%Y-%m-%d %H:%M:%S")
,axis=1)
RawData['PersonID']=RawData.apply(lambda row:
str(uuid.uuid4())
,axis=1)
################################################################
Data=RawData.copy()
Data.drop('BirthDateUTC', axis=1,inplace=True)
Data.drop('BirthDateISO', axis=1,inplace=True)
indexed_data = Data.set_index(['PersonID'])
print('################################')
#################################################################
print('################')
sTable='Process_Person'
print('Storing :',sDatabaseName,' Table:',sTable)
indexed_data.to_sql(sTable, conn1, if_exists="replace")
print('################')
################################################################
PersonHubRaw=Data[['PersonID','FirstName','SecondName','LastName','BirthDateKey']]
PersonHubRaw['PersonHubID']=RawData.apply(lambda row:
str(uuid.uuid4())
,axis=1)
PersonHub=PersonHubRaw.drop_duplicates(subset=None, \
keep='first',\
inplace=False)
indexed_PersonHub = PersonHub.set_index(['PersonHubID'])
sTable = 'Hub-Person'
print('Storing :',sDatabaseName,' Table:',sTable)
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
It will apply golden nominal rules by assuming nobody born before January 1, 1900, droping to two
ISO complex date time structures, as the code does not translate into SQLite’s data types and saves
your new golden nominal to a CSV file.
Load the person into the data vault
========== RESTART: C:\VKHCG\04-Clark\03-Process\Process-People.py ==========
################################
using
win32
################################ ################################
Loading : C:/VKHCG/04-Clark/02-Assess/01-EDS/02-Python/Assess_People.csv
################################
C:/VKHCG/04-Clark/02-Assess/01-EDS/02-Python/Assess_People.csv
################################
################
Storing : C:/VKHCG/88-DV/datavault.db
################
Storing : C:/VKHCG/88-DV/datavault.db
Storing : C:/VKHCG/88-DV/datavault.db
################################
Table: Process_Person
Table: Satellite-Person-Gender Table: Satellite-Person-Names
Storing : C:/VKHCG/04-Clark/03-Process/01-EDS/02-Python/Satellite-Person-Names.csv
################################
################################ ################
Vacuum Databases ################
### Done!! ############################################
Vehicles
The international classification of vehicles is a complex process. There are standards, but these are
not universally applied or similar between groups or countries.
Let’s load the vehicle data for Hillman Ltd into the data vault, as we will need it later. Create a new
file named Process-Vehicle-Logistics.py in the Python editor in directory ..\VKHCG\03-Hillman\03-
Process. ################################################################
# -*- coding: utf-8 -*- ################################################################
import sys
import os
import pandas as pd
import sqlite3 as sq
from pandas.io import sql import uuid
pd.options.mode.chained_assignment = None
################################################################
if sys.platform == 'linux': Base=os.path.expanduser('~') + '/VKHCG'
else:
Base='C:/VKHCG' print('################################')
print('Working Base :',Base, ' using ', sys.platform)
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
print('################################')
################################################################
Company='03-Hillman' InputDir='00-RawData' InputFileName='VehicleData.csv'
################################################################
sDataBaseDir=Base + '/' + Company + '/03-Process/SQLite' if not os.path.exists(sDataBaseDir):
os.makedirs(sDataBaseDir)
################################################################
sDatabaseName=sDataBaseDir + '/Hillman.db' conn1 = sq.connect(sDatabaseName)
################################################################
sDataVaultDir=Base + '/88-DV'
if not os.path.exists(sDataBaseDir): os.makedirs(sDataBaseDir)
################################################################
sDatabaseName=sDataVaultDir + '/datavault.db' conn2 = sq.connect(sDatabaseName)
################################################################
sFileName=Base + '/' + Company + '/' + InputDir + '/' + InputFileName print('###########')
print('Loading :',sFileName) VehicleRaw=pd.read_csv(sFileName,header=0,low_memory=False,
encoding="latin-1") ################################################################
sTable='Process_Vehicles'
print('Storing :',sDatabaseName,' Table:',sTable) VehicleRaw.to_sql(sTable, conn1,
if_exists="replace")
################################################################
VehicleRawKey=VehicleRaw[['Make','Model']].copy()
VehicleKey=VehicleRawKey.drop_duplicates()
################################################################
VehicleKey['ObjectKey']=VehicleKey.apply(lambda row:
str('('+ str(row['Make']).strip().replace(' ', '-').replace('/', '-').lower() +
')-(' + (str(row['Model']).strip().replace(' ', '-').replace(' ', '-').lower())
+')')
,axis=1) ################################################################
VehicleKey['ObjectType']=VehicleKey.apply(lambda row: 'vehicle'
,axis=1) ################################################################
VehicleKey['ObjectUUID']=VehicleKey.apply(lambda row: str(uuid.uuid4())
,axis=1) ################################################################
### Vehicle Hub ################################################################
#
VehicleHub=VehicleKey[['ObjectType','ObjectKey','ObjectUUID']].copy()
VehicleHub.index.name='ObjectHubID'
sTable = 'Hub-Object-Vehicle'
print('Storing :',sDatabaseName,' Table:',sTable) VehicleHub.to_sql(sTable, conn2,
if_exists="replace")
################################################################
### Vehicle Satellite ################################################################
#
VehicleSatellite=VehicleKey[['ObjectType','ObjectKey','ObjectUUID','Make','Model']].copy()
VehicleSatellite.index.name='ObjectSatelliteID'
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
################################################################
### Vehicle Dimension
################################################################
sView='Dim-Object'
print('Storing :',sDatabaseName,' View:',sView)
sSQL="CREATE VIEW IF NOT EXISTS [" + sView + "] AS" sSQL=sSQL+ " SELECT DISTINCT"
H.ObjectType,"
H.ObjectKey AS VehicleKey," TRIM(S.Make) AS VehicleMake," TRIM(S.Model) AS VehicleModel"
print('################')
print('Loading :',sDatabaseName,' Table:',sView) sSQL=" SELECT DISTINCT"
sSQL=sSQL+ " VehicleMake," sSQL=sSQL+ " VehicleModel" sSQL=sSQL+ " FROM"
sSQL=sSQL+ " [" + sView + "]" sSQL=sSQL+ " ORDER BY"
sSQL=sSQL+ " VehicleMake" sSQL=sSQL+ " AND"
DimObjectData.index.name='ObjectDimID'
DimObjectData.sort_values(['VehicleMake','VehicleModel'],inplace=True, ascending=True)
print('################')
print(DimObjectData)
#################################################################
print('################')
print('Vacuum Databases') sSQL="VACUUM;"
sql.execute(sSQL,conn1) sql.execute(sSQL,conn2)
print('################')
#################################################################
conn1.close() conn2.close()
################################################################# #
print('### Done!! ############################################')
#################################################################
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Output:
Human-Environment Interaction
The interaction of humans with their environment is a major relationship that guides people’s
behavior and the characteristics of the location. Activities such as mining and other industries, roads,
and landscaping at a location create both positive and negative effects on the environment, but also on
humans. A location earmarked as a green belt, to assist in reducing the carbon footprint, or a new
interstate change its current and future characteristics. The location is a main data source for the data
science, and, normally, we find unknown or unexpected effects on the data insights. In the Python
editor, open a new file named Process_Location.py in directory ..\VKHCG\01-Vermeulen\03-Process.
################################################################
# -*- coding: utf-8 -*- ################################################################
import sys import os
import pandas as pd import sqlite3 as sq
from pandas.io import sql import uuid
################################################################ Base='C:/VKHCG'
print('################################')
print('Working Base :',Base, ' using ', sys.platform) print('################################')
################################################################
Company='01-Vermeulen' InputAssessGraphName='Assess_All_Animals.gml' EDSAssessDir='02-
Assess/01-EDS' InputAssessDir=EDSAssessDir + '/02-Python'
################################################################
sFileAssessDir=Base + '/' + Company + '/' + InputAssessDir if not os.path.exists(sFileAssessDir):
os.makedirs(sFileAssessDir)
################################################################
sDataBaseDir=Base + '/' + Company + '/03-Process/SQLite' if not os.path.exists(sDataBaseDir):
os.makedirs(sDataBaseDir)
################################################################
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Output:
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Practical 7
Transforming Data
The Transform superstep allows you, as a data scientist, to take data from the data vault and formulate
answers to questions raised by your investigations. The transformation step is the data science process
that converts results into insights. It takes standard data science techniques and methods to attain
insight and knowledge about the data that then can be transformed into actionable decisions, which,
through storytelling, you can explain to non-data scientists what you have discovered in the data lake.
################################################################
# -*- coding: utf-8 -*- ################################################################
import sys import os
from datetime
import datetime from pytz
import timezone
import pandas as pd
import sqlite3 as sq
import uuid
pd.options.mode.chained_assignment = None
################################################################
Base='C:/VKHCG'
print('################################')
print('Working Base :',Base, ' using ', sys.platform)
print('################################')
################################################################
Company='01-Vermeulen' InputDir='00-RawData' InputFileName='VehicleData.csv'
################################################################
sDataBaseDir=Base + '/' + Company + '/04-Transform/SQLite' if not os.path.exists(sDataBaseDir):
os.makedirs(sDataBaseDir)
################################################################
sDatabaseName=sDataBaseDir + '/Vermeulen.db' conn1 = sq.connect(sDatabaseName)
################################################################
sDataVaultDir=Base + '/88-DV'
if not os.path.exists(sDataVaultDir):
os.makedirs(sDataVaultDir)
################################################################
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
sDataWarehouseDir=Base + '/99-DW'
if not os.path.exists(sDataWarehouseDir):
os.makedirs(sDataWarehouseDir)
################################################################
sDatabaseName=sDataWarehouseDir + '/datawarehouse.db'
conn3 = sq.connect(sDatabaseName)
################################################################
print('\n#################################')
print('Time Category') print('UTC Time')
BirthDateUTC = datetime(1960,12,20,10,15,0)
BirthDateZoneUTC=BirthDateUTC.replace(tzinfo=timezone('UTC'))
BirthDateZoneStr=BirthDateZoneUTC.strftime("%Y-%m-%d %H:%M:%S")
BirthDateZoneUTCStr=BirthDateZoneUTC.strftime("%Y-%m-%d %H:%M:%S (%Z) (%z)")
print(BirthDateZoneUTCStr)
print('#################################')
print('Birth Date in Reykjavik :')
BirthZone = 'Atlantic/Reykjavik'
BirthDate = BirthDateZoneUTC.astimezone(timezone(BirthZone))
BirthDateStr=BirthDate.strftime("%Y-%m-%d %H:%M:%S (%Z) (%z)")
BirthDateLocal=BirthDate.strftime("%Y-%m-%d %H:%M:%S") print(BirthDateStr)
print('#################################')
################################################################
IDZoneNumber=str(uuid.uuid4())
sDateTimeKey=BirthDateZoneStr.replace(' ','-').replace(':','-')
TimeLine=[('ZoneBaseKey', ['UTC']),
('IDNumber', [IDZoneNumber]), ('DateTimeKey', [sDateTimeKey]), ('UTCDateTimeValue',
[BirthDateZoneUTC]), ('Zone', [BirthZone]),
('DateTimeValue', [BirthDateStr])]
TimeFrame = pd.DataFrame.from_items(TimeLine)
################################################################
TimeHub=TimeFrame[['IDNumber','ZoneBaseKey','DateTimeKey','DateTimeValue']]
TimeHubIndex=TimeHub.set_index(['IDNumber'],inplace=False)
################################################################
sTable = 'Hub-Time-Gunnarsson'
print('\n#################################')
print('Storing :',sDatabaseName,'\n Table:',sTable)
print('\n#################################')
TimeHubIndex.to_sql(sTable, conn2, if_exists="replace")
sTable = 'Dim-Time-Gunnarsson' TimeHubIndex.to_sql(sTable, conn3, if_exists="replace")
################################################################
TimeSatellite=TimeFrame[['IDNumber','DateTimeKey','Zone','DateTimeValue']]
TimeSatelliteIndex=TimeSatellite.set_index(['IDNumber'],inplace=False)
################################################################
BirthZoneFix=BirthZone.replace(' ','-').replace('/','-')
sTable = 'Satellite-Time-' + BirthZoneFix + '-Gunnarsson'
print('\n#################################')
print('Storing :',sDatabaseName,'\n Table:',sTable) print('\n#################################')
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Output : Guðmundur Gunnarsson was born on December 20, 1960, at 9:15 in Landspítali,Hringbraut
101, 101 Reykjavík, Iceland.
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
You must build three items: dimension Person, dimension Time, and factPersonBornAtTime. Open
your Python editor and create a file named Transform-Gunnarsson-Sun-Model.py in directory
C:\VKHCG\01-Vermeulen\04-Transform.
################################################################
# -*- coding: utf-8 -*- ################################################################
import sys import os
from datetime
import datetime from pytz
import timezone
import pandas as pd
import sqlite3 as sq
import uuid
pd.options.mode.chained_assignment = None
################################################################
if sys.platform == 'linux':
Base=os.path.expanduser('~') + '/VKHCG'
else:
Base='C:/VKHCG'
print('################################')
print('Working Base :',Base, ' using ', sys.platform)
print('################################')
################################################################
Company='01-Vermeulen'
################################################################
sDataBaseDir=Base + '/' + Company + '/04-Transform/SQLite' if not os.path.exists(sDataBaseDir):
os.makedirs(sDataBaseDir)
################################################################
sDatabaseName=sDataBaseDir + '/Vermeulen.db' conn1 = sq.connect(sDatabaseName)
################################################################
sDataWarehousetDir=Base + '/99-DW'
if not os.path.exists(sDataWarehousetDir):
os.makedirs(sDataWarehousetDir)
################################################################
sDatabaseName=sDataWarehousetDir + '/datawarehouse.db' conn2 = sq.connect(sDatabaseName)
################################################################
print('\n#################################')
print('Time Dimension') BirthZone = 'Atlantic/Reykjavik'
BirthDateUTC = datetime(1960,12,20,10,15,0)
BirthDateZoneUTC=BirthDateUTC.replace(tzinfo=timezone('UTC'))
BirthDateZoneStr=BirthDateZoneUTC.strftime("%Y-%m-%d %H:%M:%S")
BirthDateZoneUTCStr=BirthDateZoneUTC.strftime("%Y-%m-%d %H:%M:%S (%Z) (%z)")
BirthDate = BirthDateZoneUTC.astimezone(timezone(BirthZone))
BirthDateStr=BirthDate.strftime("%Y-%m-%d %H:%M:%S (%Z) (%z)")
BirthDateLocal=BirthDate.strftime("%Y-%m-%d %H:%M:%S")
################################################################
IDTimeNumber=str(uuid.uuid4())
TimeLine=[('TimeID', [IDTimeNumber]),
('UTCDate', [BirthDateZoneStr]), ('LocalTime', [BirthDateLocal]), ('TimeZone', [BirthZone])]
TimeFrame = pd.DataFrame.from_items(TimeLine)
################################################################
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
DimTime=TimeFrame DimTimeIndex=DimTime.set_index(['TimeID'],inplace=False)
################################################################
sTable = 'Dim-Time' print('\n#################################')
print('Storing :',sDatabaseName,'\n Table:',sTable)
print('\n#################################')
DimTimeIndex.to_sql(sTable, conn1, if_exists="replace")
DimTimeIndex.to_sql(sTable, conn2, if_exists="replace")
################################################################
print('\n#################################')
print('Dimension Person')
print('\n#################################')
FirstName = 'Guðmundur' LastName = 'Gunnarsson'
###############################################################
IDPersonNumber=str(uuid.uuid4())
PersonLine=[('PersonID', [IDPersonNumber]),
('FirstName', [FirstName]),
('LastName', [LastName]),
('Zone', ['UTC']),
('DateTimeValue', [BirthDateZoneStr])]
PersonFrame = pd.DataFrame.from_items(PersonLine)
################################################################
DimPerson=PersonFrame DimPersonIndex=DimPerson.set_index(['PersonID'],inplace=False)
################################################################
sTable = 'Dim-Person' print('\n#################################')
print('Storing :',sDatabaseName,'\n Table:',sTable) print('\n#################################')
DimPersonIndex.to_sql(sTable, conn1, if_exists="replace")
DimPersonIndex.to_sql(sTable, conn2, if_exists="replace")
################################################################
print('\n#################################')
print('Fact - Person - time') print('\n#################################')
IDFactNumber=str(uuid.uuid4())
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Output:
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
conn2 = sq.connect(sDatabaseName)
################################################################
sDataWarehouseDir=Base + '/99-DW'
if not os.path.exists(sDataWarehouseDir):
os.makedirs(sDataWarehouseDir)
################################################################
sDatabaseName=sDataWarehouseDir + '/datawarehouse.db'
conn3 = sq.connect(sDatabaseName)
################################################################
sSQL=" SELECT DateTimeValue FROM [Hub-Time];"
DateDataRaw=pd.read_sql_query(sSQL, conn2)
DateData=DateDataRaw.head(1000)
print(DateData) ################################################################
print('\n#################################')
print('Time Dimension')
print('\n#################################')
t=0
mt=DateData.shape[0]
for i in range(mt):
BirthZone = ('Atlantic/Reykjavik','Europe/London','UCT')
for j in range(len(BirthZone)):
t+=1
print(t,mt*3)
BirthDateUTC = datetime.strptime(DateData['DateTimeValue'][i],"%Y-%m-%d %H:%M:%S")
BirthDateZoneUTC=BirthDateUTC.replace(tzinfo=timezone('UTC'))
BirthDateZoneStr=BirthDateZoneUTC.strftime("%Y-%m-%d %H:%M:%S")
BirthDateZoneUTCStr=BirthDateZoneUTC.strftime("%Y-%m-%d %H:%M:%S (%Z) (%z)")
BirthDate = BirthDateZoneUTC.astimezone(timezone(BirthZone[j]))
BirthDateStr=BirthDate.strftime("%Y-%m-%d %H:%M:%S (%Z) (%z)")
BirthDateLocal=BirthDate.strftime("%Y-%m-%d %H:%M:%S")
################################################################
IDTimeNumber=str(uuid.uuid4()) TimeLine=[('TimeID', [str(IDTimeNumber)]),
('UTCDate', [str(BirthDateZoneStr)]), ('LocalTime', [str(BirthDateLocal)]), ('TimeZone',
[str(BirthZone)])]
if t==1:
TimeFrame = pd.DataFrame.from_items(TimeLine)
else:
TimeRow = pd.DataFrame.from_items(TimeLine)
TimeFrame=TimeFrame.append(TimeRow)
################################################################
DimTime=TimeFrame
DimTimeIndex=DimTime.set_index(['TimeID'],inplace=False)
################################################################
sTable = 'Dim-Time'
print('\n#################################')
print('Storing :',sDatabaseName,'\n Table:',sTable)
print('\n#################################')
DimTimeIndex.to_sql(sTable, conn1, if_exists="replace")
DimTimeIndex.to_sql(sTable, conn3, if_exists="replace")
################################################################
sSQL=" SELECT " + \
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
" FirstName," + \
" SecondName," + \ " LastName," + \
" BirthDateKey " + \
" FROM [Hub-Person];" PersonDataRaw=pd.read_sql_query(sSQL, conn2)
PersonData=PersonDataRaw.head(1000)
################################################################
print('\n#################################')
print('Dimension Person')
print('\n#################################')
t=0
mt=DateData.shape[0]
for i in range(mt):
t+=1
print(t,mt)
FirstName = str(PersonData["FirstName"])
SecondName = str(PersonData["SecondName"])
if len(SecondName) > 0:
SecondName=""
LastName = str(PersonData["LastName"])
BirthDateKey = str(PersonData["BirthDateKey"])
###############################################################
IDPersonNumber=str(uuid.uuid4())
PersonLine=[('PersonID', [str(IDPersonNumber)]),
('FirstName', [FirstName]), ('SecondName', [SecondName]), ('LastName', [LastName]), ('Zone',
[str('UTC')]),
('BirthDate', [BirthDateKey])]
if t==1:
PersonFrame = pd.DataFrame.from_items(PersonLine)
else:
PersonRow = pd.DataFrame.from_items(PersonLine)
PersonFrame = PersonFrame.append(PersonRow)
################################################################
DimPerson=PersonFrame print(DimPerson)
DimPersonIndex=DimPerson.set_index(['PersonID'],inplace=False)
################################################################
sTable = 'Dim-Person' print('\n#################################')
print('Storing :',sDatabaseName,'\n Table:',sTable)
print('\n#################################')
DimPersonIndex.to_sql(sTable, conn1, if_exists="replace")
DimPersonIndex.to_sql(sTable, conn3, if_exists="replace")
###############################################################
Output:
You have successfully performed data vault to data warehouse transformation.
Simple Linear Regression
Linear regression is used if there is a relationship or significant association between the variables.
This can be checked by scatterplots. If no linear association appears between the variables, fitting a
linear regression model to the data will not provide a useful model. A linear regression line has
equations in the following form:
Y = a + bX,
Where, X = explanatory variable and Y = dependent variable
b = slope of the line
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
################################################################
# -*- coding: utf-8 -*- ################################################################
import sys import os
import pandas as pd
import sqlite3 as sq
import matplotlib.pyplot as plt
import numpy as np
from sklearn
import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
################################################################
Base='C:/VKHCG'
print('################################')
print('Working Base :',Base, ' using ', sys.platform)
print('################################')
################################################################
################################################################
Company='01-Vermeulen'
################################################################
sDataBaseDir=Base + '/' + Company + '/04-Transform/SQLite' if not os.path.exists(sDataBaseDir):
os.makedirs(sDataBaseDir)
################################################################
sDatabaseName=sDataBaseDir + '/Vermeulen.db'
conn1 = sq.connect(sDatabaseName)
################################################################
sDataVaultDir=Base + '/88-DV'
if not os.path.exists(sDataVaultDir):
os.makedirs(sDataVaultDir)
################################################################
sDatabaseName=sDataVaultDir + '/datavault.db' conn2 = sq.connect(sDatabaseName)
################################################################
sDataWarehouseDir=Base + '/99-DW'
if not os.path.exists(sDataWarehouseDir):
os.makedirs(sDataWarehouseDir)
################################################################
sDatabaseName=sDataWarehouseDir + '/datawarehouse.db'
conn3 = sq.connect(sDatabaseName)
################################################################
t=0
tMax=((300-100)/10)*((300-30)/5)
for heightSelect in range(100,300,10):
for weightSelect in range(30,300,5):
height = round(heightSelect/100,3)
weight = int(weightSelect)
bmi = weight/(height*height)
if bmi <= 18.5:
BMI_Result=1
elif bmi > 18.5 and bmi < 25:
BMI_Result=2
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
plt.axis('tight')
plt.title("BMI Curve")
plt.xlabel("Height(meters)")
plt.ylabel("Weight(kg)")
plt.plot()
# Load the diabetes dataset diabetes = datasets.load_diabetes()
# Use only one feature
diabetes_X = diabetes.data[:, np.newaxis, 2] diabetes_X_train = diabetes_X[:-30] diabetes_X_test =
diabetes_X[-50:] diabetes_y_train = diabetes.target[:-30] diabetes_y_test = diabetes.target[-50:]
regr = linear_model.LinearRegression() regr.fit(diabetes_X_train, diabetes_y_train) diabetes_y_pred
= regr.predict(diabetes_X_test) print('Coefficients: \n', regr.coef_)
print("Mean squared error: %.2f"
% mean_squared_error(diabetes_y_test, diabetes_y_pred))
print('Variance score: %.2f' % r2_score(diabetes_y_test, diabetes_y_pred))
plt.scatter(diabetes_X_test, diabetes_y_test, color='black')
plt.plot(diabetes_X_test, diabetes_y_pred, color='blue', linewidth=3)
plt.xticks(())
plt.yticks(())
plt.axis('tight')
plt.title("Diabetes")
plt.xlabel("BMI")
plt.ylabel("Age")
plt.show()
Output:
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Practical 8
Aim: Organizing Data
C:\VKHCG\01-Vermeulen\05-Organise\ Organize-Horizontal.py
################################################################
# -*- coding: utf-8 -*- ################################################################
import sys
import os
import pandas as pd
import sqlite3 as sq
################################################################
Base='C:/VKHCG'
print('################################')
print('Working Base :',Base, ' using ', sys.platform)
print('################################')
################################################################
################################################################
Company='01-Vermeulen'
################################################################
sDataWarehouseDir=Base + '/99-DW'
if not os.path.exists(sDataWarehouseDir):
os.makedirs(sDataWarehouseDir)
################################################################
sDatabaseName=sDataWarehouseDir + '/datawarehouse.db'
conn1 = sq.connect(sDatabaseName)
################################################################
sDatabaseName=sDataWarehouseDir + '/datamart.db'
conn2 = sq.connect(sDatabaseName)
################################################################
print('################')
sTable = 'Dim-BMI'
print('Loading :',sDatabaseName,' Table:',sTable)
sSQL="SELECT * FROM [Dim-BMI];"
PersonFrame0=pd.read_sql_query(sSQL, conn1)
print('################')
sTable = 'Dim-BMI'
print('Loading :',sDatabaseName,' Table:',sTable)
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
print('\n#################################')
print('Storing :',sDatabaseName,'\n Table:',sTable)
print('\n#################################')
#DimPersonIndex.to_sql(sTable, conn2, if_exists="replace")
################################################################
print('################')
sTable = 'Dim-BMI'
print('Loading :',sDatabaseName,' Table:',sTable)
sSQL="SELECT * FROM [Dim-BMI];"
PersonFrame2=pd.read_sql_query(sSQL, conn2)
print('Full Data Set (Rows):', PersonFrame0.shape[0])
print('Full Data Set (Columns):', PersonFrame0.shape[1])
print('Horizontal Data Set (Rows):', PersonFrame2.shape[0])
print('Horizontal Data Set (Columns):', PersonFrame2.shape[1])
Output:
Vertical Style
Performing vertical-style slicing or subsetting of the data warehouse is achieved by applying a filter
technique that forces the data warehouse to show only the data for specific preselected filtered
outcomes against the data population. The vertical-style slicing selects the subset of columns from the
population, while preserving the rows. That is, the data science tool can see only the preselected
columns from a record for all the records in the population.
C:\VKHCG\01-Vermeulen\05-Organise\ Organize-Vertical.py
################################################################
# -*- coding: utf-8 -*- ################################################################
import sys
import os
import pandas as pd
import sqlite3 as sq
################################################################
Base='C:/VKHCG'
print('################################')
print('Working Base :',Base, ' using ', sys.platform)
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
print('################################')
################################################################
################################################################
Company='01-Vermeulen'
################################################################
sDataWarehouseDir=Base + '/99-DW'
if not os.path.exists(sDataWarehouseDir):
os.makedirs(sDataWarehouseDir)
################################################################
sDatabaseName=sDataWarehouseDir + '/datawarehouse.db'
conn1 = sq.connect(sDatabaseName)
################################################################
sDatabaseName=sDataWarehouseDir + '/datamart.db'
conn2 = sq.connect(sDatabaseName)
################################################################
print('################################')
sTable = 'Dim-BMI'
print('Loading :',sDatabaseName,' Table:',sTable)
sSQL="SELECT * FROM [Dim-BMI];"
PersonFrame0=pd.read_sql_query(sSQL, conn1)
################################################################
print('################################')
sTable = 'Dim-BMI'
print('Loading :',sDatabaseName,' Table:',sTable)
print('################################')
sSQL="SELECT \
Height,\ Weight,\ Indicator\
FROM [Dim-BMI];"
PersonFrame1=pd.read_sql_query(sSQL, conn1)
################################################################
DimPerson=PersonFrame1 DimPersonIndex=DimPerson.set_index(['Indicator'],inplace=False)
################################################################
sTable = 'Dim-BMI-Vertical'
print('\n#################################')
print('Storing :',sDatabaseName,'\n Table:',sTable)
print('\n#################################')
DimPersonIndex.to_sql(sTable, conn2, if_exists="replace")
################################################################
print('################')
sTable = 'Dim-BMI-Vertical'
print('Loading :',sDatabaseName,' Table:',sTable)
sSQL="SELECT * FROM [Dim-BMI-Vertical];"
PersonFrame2=pd.read_sql_query(sSQL, conn2)
################################################################
print('################################')
print('Full Data Set (Rows):', PersonFrame0.shape[0]) print('Full Data Set (Columns):',
PersonFrame0.shape[1])
print('################################')
print('Horizontal Data Set (Rows):', PersonFrame2.shape[0])
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Output:
The vertical-style slicing selects 3 of 5 from the population, while preserving the rows [1080].
Island Style
Performing island-style slicing or subsetting of the data warehouse is achieved by applying a
combination of horizontal- and vertical-style slicing. This generates a subset of specific rows and
specific columns reduced at the same time.
C:\VKHCG\01-Vermeulen\05-Organise\ Organize-Island.py
################################################################
# -*- coding: utf-8 -*- ################################################################
import sys
import os
import pandas as pd
import sqlite3 as sq
################################################################
Base='C:/VKHCG'
print('################################')
print('Working Base :',Base, ' using ', sys.platform)
print('################################')
################################################################
################################################################
Company='01-Vermeulen'
################################################################
sDataWarehouseDir=Base + '/99-DW'
if not os.path.exists(sDataWarehouseDir):
os.makedirs(sDataWarehouseDir)
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
################################################################
sDatabaseName=sDataWarehouseDir + '/datawarehouse.db'
conn1 = sq.connect(sDatabaseName)
################################################################
sDatabaseName=sDataWarehouseDir + '/datamart.db'
conn2 = sq.connect(sDatabaseName)
################################################################
print('################')
sTable = 'Dim-BMI'
print('Loading :',sDatabaseName,' Table:',sTable)
sSQL="SELECT * FROM [Dim-BMI];"
PersonFrame0=pd.read_sql_query(sSQL, conn1)
################################################################
print('################')
sTable = 'Dim-BMI'
print('Loading :',sDatabaseName,' Table:',sTable)
sSQL="SELECT \
Height,\ Weight,\ Indicator\
FROM [Dim-BMI]\
WHERE Indicator > 2\
ORDER BY \
Height,\ Weight;"
PersonFrame1=pd.read_sql_query(sSQL, conn1)
################################################################
DimPerson=PersonFrame1 DimPersonIndex=DimPerson.set_index(['Indicator'],inplace=False)
################################################################
sTable = 'Dim-BMI-Vertical' print('\n#################################')
print('Storing :',sDatabaseName,'\n Table:',sTable)
print('\n#################################')
DimPersonIndex.to_sql(sTable, conn2, if_exists="replace")
################################################################
print('################################')
sTable = 'Dim-BMI-Vertical'
print('Loading :',sDatabaseName,' Table:',sTable)
print('################################')
sSQL="SELECT * FROM [Dim-BMI-Vertical];"
PersonFrame2=pd.read_sql_query(sSQL, conn2)
################################################################
print('################################')
print('Full Data Set (Rows):', PersonFrame0.shape[0])
print('Full Data Set (Columns):', PersonFrame0.shape[1])
print('################################')
print('Horizontal Data Set (Rows):', PersonFrame2.shape[0])
print('Horizontal Data Set (Columns):', PersonFrame2.shape[1])
print('################################')
################################################################
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Output:
C:\VKHCG\01-Vermeulen\05-Organise\ Organize-Secure-Vault.py
################################################################
# -*- coding: utf-8 -*- ################################################################
import sys
import os
import pandas as pd
import sqlite3 as sq
################################################################
Base='C:/VKHCG'
print('################################')
print('Working Base :',Base, ' using ', sys.platform)
print('################################')
################################################################
################################################################
Company='01-Vermeulen'
################################################################
sDataWarehouseDir=Base + '/99-DW'
if not os.path.exists(sDataWarehouseDir): os.makedirs(sDataWarehouseDir)
################################################################
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
sDatabaseName=sDataWarehouseDir + '/datawarehouse.db'
conn1 = sq.connect(sDatabaseName)
################################################################
sDatabaseName=sDataWarehouseDir + '/datamart.db'
conn2 = sq.connect(sDatabaseName)
################################################################
print('################')
sTable = 'Dim-BMI'
print('Loading :',sDatabaseName,' Table:',sTable)
sSQL="SELECT * FROM [Dim-BMI];"
PersonFrame0=pd.read_sql_query(sSQL, conn1)
################################################################
print('################')
sTable = 'Dim-BMI'
print('Loading :',sDatabaseName,' Table:',sTable)
sSQL="SELECT \
Height,\ Weight,\ Indicator,\ CASE Indicator\
WHEN 1 THEN 'Pip'\
WHEN 2 THEN 'Norman'\ WHEN 3 THEN 'Grant'\ ELSE 'Sam'\
END AS Name\ FROM [Dim-BMI]\
WHERE Indicator > 2\
ORDER BY \
Height,\ Weight;"
PersonFrame1=pd.read_sql_query(sSQL, conn1)
################################################################
DimPerson=PersonFrame1 DimPersonIndex=DimPerson.set_index(['Indicator'],inplace=False)
################################################################
sTable = 'Dim-BMI-Secure'
print('\n#################################')
print('Storing :',sDatabaseName,'\n Table:',sTable)
print('\n#################################')
DimPersonIndex.to_sql(sTable, conn2, if_exists="replace")
################################################################
print('################################')
sTable = 'Dim-BMI-Secure'
print('Loading :',sDatabaseName,' Table:',sTable)
print('################################')
sSQL="SELECT * FROM [Dim-BMI-Secure] WHERE Name = 'Sam';"
PersonFrame2=pd.read_sql_query(sSQL, conn2)
################################################################
print('################################')
print('Full Data Set (Rows):', PersonFrame0.shape[0])
print('Full Data Set (Columns):', PersonFrame0.shape[1])
print('################################')
print('Horizontal Data Set (Rows):', PersonFrame2.shape[0])
print('Horizontal Data Set (Columns):', PersonFrame2.shape[1])
print('Only Sam Data')
print(PersonFrame2.head())
print('################################')
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
################################################################
Output:
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Practical 9
Aim: Generating Data
Report Superstep
The Report superstep is the step in the ecosystem that enhances the data science findings with the art
of storytelling and data visualization. You can perform the best data science, but if you cannot execute
a respectable and trustworthy Report step by turning your data science into actionable business
insights, you have achieved no advantage for your business.
Vermeulen PLC
Vermeulen requires a map of all their customers’ data links. Can you provide a report to deliver this? I
will guide you through an example that delivers this requirement.
C:\VKHCG\01-Vermeulen\06-Report\Raport-Network-Routing-Customer.py
################################################################
import sys
import os
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
################################################################
pd.options.mode.chained_assignment = None
################################################################
if sys.platform == 'linux':
Base=os.path.expanduser('~') + 'VKHCG'
else:
Base='C:/VKHCG' ################################################################
print('################################')
print('Working Base :',Base, ' using ', sys.platform)
print('################################')
################################################################
sInputFileName='02-Assess/01-EDS/02-Python/Assess-Network-Routing-Customer.csv'
################################################################
sOutputFileName1='06-Report/01-EDS/02-Python/Report-Network-Routing-Customer.gml'
sOutputFileName2='06-Report/01-EDS/02-Python/Report-Network-Routing-Customer.png'
Company='01-Vermeulen'
################################################################
################################################################
### Import Country Data
################################################################
sFileName=Base + '/' + Company + '/' + sInputFileName
print('################################')
print('Loading :',sFileName)
print('################################')
CustomerDataRaw=pd.read_csv(sFileName,header=0,low_memory=False, encoding="latin-1")
CustomerData=CustomerDataRaw.head(100)
print('Loaded Country:',CustomerData.columns.values)
print('################################')
################################################################
print(CustomerData.head())
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
print(CustomerData.shape)
################################################################
G=nx.Graph()
for i in range(CustomerData.shape[0]):
for j in range(CustomerData.shape[0]):
Node0=CustomerData['Customer_Country_Name'][i]
Node1=CustomerData['Customer_Country_Name'][j]
if Node0 != Node1:
G.add_edge(Node0,Node1)
print('Nodes:', G.number_of_nodes())
print('Edges:', G.number_of_edges())
################################################################
sFileName=Base + '/' + Company + '/' + sOutputFileName1
print('################################')
print('Storing :',sFileName)
print('################################')
nx.write_gml(G, sFileName)
################################################################
sFileName=Base + '/' + Company + '/' + sOutputFileName2
print('################################')
print('Storing Graph Image:',sFileName)
print('################################')
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Krennwallner AG
The Krennwallner marketing department wants to deploy the locations of the billboards onto the
company web server. Can you prepare three versions of the locations’ web pages?
• Locations clustered into bubbles when you zoom out
• Locations as pins
• Locations as heat map
################################################################
# -*- coding: utf-8 -*- ################################################################
import sys
import os
import pandas as pd
from folium.plugins
import FastMarkerCluster, HeatMap from folium
import Marker, Map
import webbrowser ################################################################
Base='C:/VKHCG'
print('################################')
print('Working Base :',Base, ' using ', sys.platform)
print('################################')
################################################################
sFileName=Base+'/02-Krennwallner/01-Retrieve/01-EDS/02-
Python/Retrieve_DE_Billboard_Locations.csv' df =
pd.read_csv(sFileName,header=0,low_memory=False, encoding="latin-1")
df.fillna(value=0, inplace=True) print(df.shape)
################################################################
t=0
for i in range(df.shape[0]):
try:
sLongitude=df["Longitude"][i]
sLongitude=float(sLongitude)
except Exception: sLongitude=float(0.0)
try:
sLatitude=df["Latitude"][i]
sLatitude=float(sLatitude)
except
Exception: sLatitude=float(0.0)
try:
sDescription=df["Place_Name"][i] + ' (' + df["Country"][i]+')'
except
Exception:
sDescription='VKHCG'
if sLongitude != 0.0 and sLatitude != 0.0:
DataClusterList=list([sLatitude, sLongitude]) DataPointList=list([sLatitude, sLongitude,
sDescription])
t+=1
if t==1:
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
DataCluster=[DataClusterList]
DataPoint=[DataPointList]
else:
DataCluster.append(DataClusterList)
DataPoint.append(DataPointList)
data=DataCluster pins=pd.DataFrame(DataPoint)
pins.columns = [ 'Latitude','Longitude','Description']
################################################################
stops_map1 = Map(location=[48.1459806, 11.4985484], zoom_start=5)
marker_cluster = FastMarkerCluster(data).add_to(stops_map1)
sFileNameHtml=Base+'/02-Krennwallner/06-Report/01-EDS/02-Python/Billboard1.html'
stops_map1.save(sFileNameHtml)
webbrowser.open('file://' + os.path.realpath(sFileNameHtml))
################################################################
stops_map2 = Map(location=[48.1459806, 11.4985484], zoom_start=5)
for name, row in pins.iloc[:100].iterrows():
Marker([row["Latitude"],row["Longitude"]], popup=row["Description"]).add_to(stops_map2)
sFileNameHtml=Base+'/02-Krennwallner/06-Report/01-EDS/02-Python/Billboard2.html'
stops_map2.save(sFileNameHtml)
webbrowser.open('file://' + os.path.realpath(sFileNameHtml))
################################################################
stops_heatmap = Map(location=[48.1459806, 11.4985484], zoom_start=5)
stops_heatmap.add_child(HeatMap([[row["Latitude"], row["Longitude"]] for name, row in
pins.iloc[:100].iterrows()]))
sFileNameHtml=Base+'/02-Krennwallner/06-Report/01-EDS/02-Python/Billboard_heatmap.html'
stops_heatmap.save(sFileNameHtml)
webbrowser.open('file://' + os.path.realpath(sFileNameHtml))
################################################################ print('### Done!!
############################################')
################################################################
Output:
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Practical 10
Power BI is a Data Visualiza on and Business Intelligence tool that converts data from different data
sources to interac ve dashboards and BI reports. Power BI suite provides mul ple so ware,
connector, and services - Power BI desktop, Power BI service based on Saas, and mobile Power BI
apps available for different pla orms. These set of services are used by business users to consume
data and build BI reports. Power BI desktop app is used to create reports, while Power BI Services
(So ware as a Service - SaaS) is used to publish the reports, and Power BI mobile app is used to view
the reports and dashboards. Visualiza ons are used to effec vely present your data and are the basic
building blocks of any Business Intelligence tool. Power BI contains various default data visualiza on
components that include simple bar charts to pie charts to maps, and also complex models such as
waterfalls, funnels, gauges, and many other components. In Power BI, you can create visualiza on in
two ways. First is by adding from the right side pane to Report Canvas. By default, it is the table type
visualiza on, which is selected in Power BI. Another way is to drag the fields from right side bar to
the axis and value axis under Visualiza on. You can add mul ple fields to each axis as per the
requirement.
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
3. In the Open File dialog box, select the Products.xlsx file click on open
4. Navigator Dialog box will open, Select Product table and Click on Transform Data
5. In Query Editor, select the ProductID, ProductName, Quan tyPerUnit, and UnitsInStock columns.
(Use Ctrl+ Click to select more than one columns , or Shi +Click to select columns that are beside
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
each other). . Select Remove Columns -> Remove Other Columns from the ribbon, or right-click on a
columns header and click Remove Other Columns.
6. Change the data type of the UnitsInStock column. Select UnitsInStock Column > select Data Type
drop-down bu on > Select Whole Number if not already selected. Click on Close and Apply bu on.
Task 2: Import order data from an OData feed 1. Click on Get Data > Select OData Feed > In OData
Feed dialog box paste the link of Northwind OData Feed –
‘h p://services.odata.org/V3/Northwind/Northwind.svc/’
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
4. In the Query View, scroll to the Order_Details column. In the Order_Details column, select the
expand icon. In the Expand drop-down, DeSelect (Select All Columns) to clear all columns. Select
ProductID, UnitPrice, and Quan ty. Click OK. The Expand opera on combines columns from a related
table into a subject table. When the query runs, rows from the related table (Order_Details) are
combined into rows of Order table.
5. Click the first column (OrderID) and Shi +Click the last column (Shipper). Now that all columns are
selected, use Ctrl+Click to unselect the following columns: OrderDate, ShipCity, ShipCountry,
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
6. In the Add Column ribbon tab, click Add Custom Column. In the Add Custom Column dialog box, in
the Custom Column Formula textbox, enter [Order_Details.UnitPrice] * [Order_Details.Quan ty]. In
the New column name textbox, enter LineTotal.
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
8.In Query Editor, drag the LineTotal column to the le , a er ShipCountry. Remove the Order_Details
from ProductID, UnitPrice and Quan ty columns. Click on Close and Apply bu on.
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Task 3: Combine the Products and Total Sales queries 1. Power BI Desktop loads the data from the
two queries. Once the data is loaded, select the Manage Rela onships bu on in Home ribbon. Click
on new and select Order and Products tables and we see that one already exists!
06 SADIYA SHAIKH
MSCIT PART I DATA SCIENCE SEM I
Task 4: Build visuals using your data 1. Click on Report, Drag UnitInStock to canva and Select Stacked
Column Chart. Create charts showing Units in Stock by Product and Total Sales by Year. Change the X-
axis and Y-axis as shown below.
2. Drag OrderDate to the canvas beneath the first chart, then drag LineTotal (again, the Fields pane)
onto the visual, then select Line Chart.
06 SADIYA SHAIKH