Data Engineering With Python - WO
Data Engineering With Python - WO
Python
Dachuri Chaitanya
[Link] (IIT Roorkee), AI Expert, 20 yrs Exp.
[Link]
Faculty Introduction
• Post graduate from IIT Roorkee
3 4
Output Output
D. Chaitanya Reddy (IIT Roorkee Alumni, AI Expert)
Ex: C, C++, Java Ex: JS, Perl, Python
Why PYTHON ?
• Developer Productivity • Huge Support Libraries
Software code
package
PYTHON P
[Link] or V Output
Python M
Interpreter
Software code
Source code byte code
package
1. Reads line by line of source code ([Link])
[Link] Output
2. Generates byte code for every line ([Link]) [Link] PVM
Using windows command prompt 1) Python installation path must be set in PATH system variable.
2) Source code ([Link]) must be available in CWD: C:\Users\Lenovo
python [Link]
or
Executes the python D:\code\[Link] To get o/p using this command
Fixed Length (No elements change possible) Variable Length (add elements, delete elements, change elements)
Faster results even with huge datasets Slow results with huge data
asarray(ndarray) – [Link](arr1)
ones_like(ndarray) – np.ones_like(arr1)
zeros_like(ndarray) – np.zeros_like(arr1)
eye(int) – [Link](6)
indentity(int) – [Link](7)
[Link] – shape of the array. Ex: (2, 3) array() - [Link]([1, 2, 3], dtype=np.float64)
arr – arr
Accessing rows (elements) of 2D array
1/arr
Accessing sub
Indexing, slicing
arr1 < arr2
portion of 2D array. – 2D array
arr == 0
Comparison
data = [Link]([[4, 7], [0, 2], [-5, 6], [0, arr2d[[1, 5, 7], [0, 3, 1]] = 0 ➔ (1, 0), (5, 3), (7, 1)
0], [1, 2], [-12, -4], [3, 4]])
names == ‘bob’, names != ‘joe’, ~(names == arr = [Link](15).reshape((3, 5)) Matrix operations
‘will’)
arr.T Matrix Transpose. Matrix multiplication
data[names==‘bob’]
[Link](arr1, arr2) or arr1.T @ arr2
data[~(names==‘joe’)]=7 samples = [Link].standard_normal(size=(4, 4))
data[names==bob, 1] Boolean #Generating array of 2, 3 shape where every element is randomly choosen between 0 to 100
Indexing data(IIT=Roorkee
D. Chaitanya Reddy [Link](100,
Alumni, AI Expert) size=(2, 3))
data[names==‘joe’, 1:] data = [Link](100, size=15)
Universal Functions
Takes 2 arrays and
[Link](arr), [Link](arr) [Link](arr1, arr2) returns single array
[Link](arr),
Unary ufunc [Link](arr1, 4)
[Link](arr), [Link]()
Array operation code:
rarr = [Link](cond, xarr, yarr) [Link](arr), [Link](axis=1), [Link](axis=0)
[Link](axis=0), [Link](axis=1)
mean = [Link](0)
Rule:
Two arrays are compatible for broadcasting if for
each tailing dimension (starting from the end) the
axis length match or if either of the lengths is 1.
Broadcasting is performed over the missing or
length 1 dimensions.
mean = [Link](1)
mean = [Link](4, 1)
arr1 = [Link](24).reshape(3, 4, 2)
s3 + s4
Series Reindexing
obi = [Link](['blue', 'purple', 'yellow'], index=[0,
2, 4])
Arithmetic operations
D. Chaitanya Reddy (IIT Roorkee Alumni, AI Expert)
with Series & DFs
Contd…
Series, DataFrames
df1 = [Link]([Link](4, 3),
s1 = [Link](range(4), index=['d', 'a', 'b', 'c’])
columns=list('bde'), index=['Utah', 'Ohio', 'Texas',
'Oregon’])
s1.sort_index() Sorting indexes, column headers
applying abs to every
[Link](df1) element in df1 df1 = [Link]([Link](8).reshape((2, 4)),
index=['three', 'one'], columns=['d', 'a', 'b', 'c’])
Applying function on 1D
def diff(x):
array (Row / Column) in DF df1.sort_index(), df1.sort_index(axis=0)
return [Link]() - [Link]()
df1.sort_index(axis=1)
Applying diff function
[Link](diff) across the rows.
s2 = [Link]([4, [Link], 7, [Link], -3, 2])
[Link](diff, axis=0) Sorting values and missing
Applying diff function s2.sort_values() values (NaN) moved to last.
across the columns.
[Link](diff, axis=1) Sorting values but,
def my_format(el): s2.sort_values(na_position='first’) NaN moved to first.
Applying function element
return f'{el:0.2f}’
wise in a DF, a Column in DF Sorting values
Applying my_format function
[Link](my_format)on all elements in DF df2 = [Link]({'b': [4, 7, -3, 2], 'a': [0, 1, 0,
1]})
Applying my_format function on
df1['e'].map(my_format) all elements in a column in DF df2.sort_values('b’)
df2.sort_values(['a',
D. Chaitanya Reddy (IIT Roorkee Alumni, AI Expert) 'b'])
Contd…
Series, DataFrames
s1 = [Link](range(5), index=['a', 'a', 'b', 'b',
'c’])
[Link]['a']
s1[[Link](['b', 'c'])]
Unique Values, Value
counts, Membership
Python have many default sentinels (empty data/invalid data/etc…) like NA, NULL, etc… All these values should
be loaded/read as NaN by default. keep_default_na=False means, all those sentinels are loaded/read as is.
df1 = [Link](sheet_name='Sheet1')
Read the data from the
More popular & versatile specified sheet name into DF
than ExcelFile()
1st row is NOT treated
df1 = pd.read_excel('[Link]’, sheet_name='Sheet1')
as column header
Indication of
expected JSON format.
3 rows with
same columns.
No Row index
names. df1 = pd.read_json(r'[Link]', orient='columns’)
3 rows of a
table.
Proper code for correct Reading of JSON:
import json
with open('[Link]','r') as f:
data = [Link]([Link]())
df1.to_json('[Link]')
df1.to_json('[Link]', orient='records')
1 2 3
1 Need username,
user = 'root' password, host, port,
password = 'python' database name details.
host = '[Link]'
port = '3306'
database = 'pythonTraining'
url = 'mysql://{0}:{1}@{2}:{3}/{4}'.format(user, password, host, port, database)
con = sqla.create_engine(url)
2
df1 = pd.read_sql('select * from students', con)
If table exists.
Table name into which D. Chaitanya Reddypossible values:
(IIT Roorkee Alumni, fail, replace, append
AI Expert)
want to load DF data.
Web Scraping
type(tables)
tables[0], tables[2]
df1.to_html()
df1 = pd.read_xml(r'[Link]')
Parse required
set of nodes
df1 = pd.read_xml(r'[Link]')
df1.to_xml(r'[Link]', row_name='store',
df1 = pd.read_xml(r'[Link]', attrs_only=True) attr_cols=['slNo'], elem_cols=['foodItem', 'price',
'quantity'])
df1 = pd.read_xml(r'[Link]', elems_only=True)
df4 = pd.read_xml(r'[Link]')
List of columns as
df1.to_xml(r'[Link]', row_name='store', index=False)
attributes of node
df1 = [Link]([[1., 6.5, 3.], [1., [Link], [Link]], [[Link], [Link], [Link]], [None, 6.5, 3.]])
[Link](thresh=2)
Number of rows to drop
which contains any missing
value.
Does not [Link]
Chaitanya Reddy (IIT Roorkee Alumni, AI Expert)
columns
Contd…
Data Cleaning
s1 = [Link]([1, [Link], 3.5, [Link], 7])
Filling NaN values in
Series
[Link](0), [Link]([Link]())
[Link](2.5)
Filling NaN values in
Fill values column wise DF
using dictionary.
[Link]({0: 0.5, 2: 10.34})
Fill with
previous values
[Link](method='ffill’)
Fill with previous
values with limit.
[Link](method='ffill', limit=2)
Transforming / Replacing
[Link](-999, [Link])
values in Series
Giving names
to categories
[Link], pd.value_counts(cats)
Manipulating String
[Link]()
values
[Link]('gmail')
[Link][:5], [Link][2:8]
[Link]()
[Link]('@', '-’)
[Link]()
D. Chaitanya Reddy (IIT Roorkee Alumni, AI Expert)
Contd…
Data Transformation
fruits = ['apple', 'orange', 'apple', 'apple'] * 2
N = len(fruits)
rng = [Link].default_rng(seed=12345)
Categorical data
df['fruit']
df['fruit'] = df['fruit'].astype('category')
df['fruit’]
pd.get_dummies(df['fruit'])
D. Chaitanya Reddy (IIT Roorkee Alumni, AI Expert)
Data Wrangling
[Link]
Hierarchical
Accessing Accessing elements indexing in Series
elements using using both outer &
outer index inner index
Converting Series
to DF.
[Link]() [Link]().stack()
Joining / Merging
DFs
[Link](df1, df2)
Joining / Merging
DFs
Default value is
‘inner’
df2 = [Link]({'key': ['a', 'b', 'd'], 'data2': range(3)}) [Link](df1, df2, how='outer')
Joining / Merging
DFs
df2 = [Link]({'key': ['a', 'b', 'd'], 'data2': range(3)}) [Link](df1, df2, how='left')
Joining / Merging
DFs
df2 = [Link]({'key': ['a', 'b', 'd'], 'data2': range(3)}) [Link](df1, df2, how='right')
left = [Link]({'key1': ['foo', 'foo', 'bar'], 'key2': ['one', 'two', 'one'], 'lval': [1, 2, 3]})
right = [Link]({'key1': ['foo', 'foo', 'bar', 'bar'], 'key2': ['one', 'one', 'one', 'two'], 'rval': [4,
5, 6, 7]})
While merging with index with right DF, the row index values of left DF preserved.
While merging with index with left DF, the row index values of right DF preserved.
While merging with columns from both DFs, row index values are NOT preserved.
left2 = [Link]([[1., 2.], [3., 4.], [5., 6.]], index=['a', 'c', 'e'], columns=['Ohio', 'Nevada'])
right2 = [Link]([[7., 8.], [9., 10.], [11., 12.], [13, 14]], index=['b', 'c', 'd', 'e'],
columns=['Missouri', 'Alabama’])
[Link](left2, right2, left_index=True, right_index=True, how='outer’)
df1 = [Link]({'a': [1., [Link], 5., [Link]], 'b': [[Link], 2., [Link], 6.], 'c': range(2, 18, 4)})
df2 = [Link]({'a': [5., 4., [Link], 3., 7.], 'd': [[Link], 3., 4., 6., 8.]})
df1.combine_first(df2)
Y – axis:
This is X-axis: indexes of Values in
one plot values in the array the each
column of
the array
Plotting a simple
X-axis: indexes of
1-D array data values
D. Chaitanyain column
Reddy ofAlumni, AI Expert)
(IIT Roorkee
the array
Contd…
Data Visualization
fig = [Link]() 1. plots can resides in a figure object.
2. Can’t have empty figure. Every figure must have at least one plot in it.
ax3 = fig.add_subplot(2, 3, 3)
ax4 = fig.add_subplot(2, 3, 4) Assigning the 3rd, 4th, 5th, 6th
ax5 = fig.add_subplot(2, 3, 5) plots to ax3, ax4, ax5, ax6
[Link]([Link](30), [Link](30)+3*[Link].standard_normal(30))
fig
Way to access
each plot in fig
line plot
D. Chaitanya Reddy (IIT Roorkee Alumni, AI Expert)
Contd…
Data Visualization
fig = [Link]() Adding a single empty
More about
ax = fig.add_subplot() plot in a figure plots
figr = [Link]()
ax1 = figr.add_subplot()
data = [Link].standard_normal(30).cumsum()
[Link](data, color='blue', linestyle='--', label='Default')
[Link](data, color='orange', linestyle='-', drawstyle='steps-post',
D. Chaitanya Reddy (IIT Roorkee Alumni, AI Expert)label='Steps-post')
[Link]()
Contd…
Data Visualization More about
fig, ax = [Link]() Adding labels to the
Adding the X-axis plots X-axis ticks and
ticks details. display style of X-
[Link]([Link].standard_normal(1000).cumsum())
ax.set_xticks([0, 250, 500, 750, 1000]) ticks labels
ax.set_xticklabels(['one', 'two', 'three', 'four', 'five'], rotation=30, fontsize=8)
ax.set_xlabel('Stages') Setting labels
ax.set_ylabel('bitcoin profit') to X, Y axes Displaying The font size of
ax.set_title('My first matplotlib plot’) labels as 30o
the labels.
Setting the
Title to plot
Plot properties can also be
[Link](title='My first matplotlib plot', xlabels='Stages') set using this method.
fig, ax = [Link]()
[Link]([Link](100).cumsum(), color='black', linestyle='solid', label='one')
Drawing three different
[Link]([Link](100).cumsum(), color='blue', linestyle='dashed', label='two')
data in the same plot
[Link]([Link](100).cumsum(), color='red', linestyle='dotted', label='three')
[Link]()
[Link]('figure', figsize=(10, 10)) Setting the figure default
Many other properties:
properties at global level.
ticks
matplotlib
grid configuration
[Link]('font', family='monospace', weight='bold', size=8) legend
Setting font properties at global level etc…