Professional Documents
Culture Documents
Week 01
Thursday 26 August 2021
number_list = []
sq_list = []
for i in range(1,25+1):
number_list.append(i)
sq_list.append(i**2)
sq_dict
Out[1]: {1: 1,
2: 4,
3: 9,
4: 16,
5: 25,
6: 36,
7: 49,
8: 64,
9: 81,
10: 100,
11: 121,
13: 169,
14: 196,
15: 225,
16: 256,
17: 289,
18: 324,
19: 361,
20: 400,
21: 441,
22: 484,
23: 529,
24: 576,
25: 625}
sq_dict2 = {}
for i in range(1,25+1):
sq_dict2.update({i : i**2})
sq_dict2
Out[2]: {1: 1,
2: 4,
3: 9,
4: 16,
5: 25,
6: 36,
7: 49,
8: 64,
9: 81,
10: 100,
11: 121,
12: 144,
13: 169,
14: 196,
15: 225,
16: 256,
17: 289,
18: 324,
19: 361,
20: 400,
21: 441,
22: 484,
23: 529,
24: 576,
25: 625}
Enter a number 12
Square of 12 is 144
Assignment 02
You are given a string that contains alphanumeric characters only. Your task is to sort the string in
the following manner:
lower_case = []
upper_case = []
odd_digits = []
even_digits = []
for c in sample_str:
if c.islower():
lower_case.append(c)
elif c.isupper():
upper_case.append(c)
elif c.isnumeric():
if int(c) % 2 == 0:
even_digits.append(c)
else:
odd_digits.append(c)
final_str = ''
final_str2 = ''.join(final_list)
print(lower_case, upper_case)
print(odd_digits, even_digits)
print(final_list)
print(final_str)
print(final_str2)
['g', 'i', 'n', 'o', 'r', 't', 'S', '1', '3', '2', '4']
ginortS1324
ginortS1324
Readability
Reuse existing code
print(a + b)
y =add_two_numbers(12, 50)
62
In [6]: print(y)
None
return a + b
x = add_two_numbers_r(12, 50)
print(x)
62
def prime_number_check(num):
if num == 1:
is_prime = False
else:
is_prime = True
if num % i == 0:
# Start if condition
is_prime = False
break
# End if condition
# End if loop
if is_prime:
else:
print(prime_number_check(user_num))
Enter a Number 12
Function Definition
def prime_number_check(num):
if num == 1:
if num % i == 0:
# Start if condition
# End if condition
# End if loop
for i in range(20):
print(i, prime_number_check(i))
0 Prime Number
2 Prime Number
3 Prime Number
5 Prime Number
11 Prime Number
13 Prime Number
17 Prime Number
19 Prime Number
In [ ]:
out_vals = mult_ops(15, 6)
type(out_vals)
Out[10]: tuple
In [11]: out_vals
In [ ]:
In [12]: p, q, r = mult_ops(12, 8)
In [13]: p
Out[13]: 20
In [14]: q
Out[14]: 4
In [15]: r
Out[15]: 96
In [ ]:
Coding Exercise
The Fibonacci Series
F(0) = 0
F(1) = 1
localhost:8888/nbconvert/html/Completed 004 2021-08-23 to 2021-09-10.ipynb?download=false 6/117
9/8/2021 Completed 004 2021-08-23 to 2021-09-10
Instructions
fib_list = [0,1]
fib_list.append(next_value)
return fib_list[num]
for i in range(20):
0, fib(0) = 0
1, fib(1) = 1
2, fib(2) = 1
3, fib(3) = 2
4, fib(4) = 3
5, fib(5) = 5
6, fib(6) = 8
7, fib(7) = 13
8, fib(8) = 21
9, fib(9) = 34
10, fib(10) = 55
11, fib(11) = 89
In [42]: fib(5000)
Out[42]: 3878968454388325633701916308325905312082127714646245106160597214895550139044037097010822
9164622106694792934528588829738134831020089549829403614301569114789383642165639441069102
1450563413370655865623825465670071252592990385493381392883637834751890876297071203333705
2923107693008518093849801803847813996748881765554653788291644268912980384613778969021502
2930824756663462249230718833248032803750391303529033045058427011476352422702109346376991
0400671417488329842289149127310405432875329804427367682297724498774987455569190770388063
7046832794811358973739993110106219308149018570815397854379195305617510761053075688783766
0336673554452588448862416192105534574936758978490279882343510235998446639348532564119522
2185956306047536464547076033090242080638258492915645287629157575914234380914230291749108
8984155209854432486594079793571316841692868039545309545388698114665082066862897420639323
4384884652409887423958738019769938203171742089322654688793640026307977800587591296713896
34214252579116872755600360311370547754724604639987588046985178408674382863125
Recursion
localhost:8888/nbconvert/html/Completed 004 2021-08-23 to 2021-09-10.ipynb?download=false 7/117
9/8/2021 Completed 004 2021-08-23 to 2021-09-10
if num == 0:
return 0
elif num == 1:
return 1
else:
rec_fib(0)
Calculating for 0
Out[36]: 0
In [33]: rec_fib(1)
Calculating for 1
Out[33]: 1
In [34]: rec_fib(2)
Calculating for 2
Calculating for 1
Calculating for 0
Out[34]: 1
In [37]: rec_fib(3)
Calculating for 3
Calculating for 2 + 1
Calculating for 2
Calculating for 1 + 0
Calculating for 1
Calculating for 0
Calculating for 1
Out[37]: 2
In [38]: rec_fib(7)
Calculating for 7
Calculating for 6 + 5
Calculating for 6
Calculating for 5 + 4
Calculating for 5
Calculating for 4 + 3
Calculating for 4
Calculating for 3 + 2
Calculating for 3
Calculating for 2 + 1
Calculating for 2
Calculating for 1 + 0
Calculating for 1
Calculating for 0
Calculating for 1
Calculating for 2
Calculating for 1 + 0
Calculating for 1
Calculating for 0
Calculating for 3
Calculating for 2 + 1
Calculating for 2
Calculating for 1 + 0
Calculating for 1
Calculating for 0
Calculating for 1
Calculating for 4
Calculating for 3 + 2
Calculating for 3
Calculating for 2 + 1
Calculating for 2
Calculating for 1 + 0
Calculating for 1
Calculating for 0
Calculating for 1
Calculating for 2
Calculating for 1 + 0
Calculating for 1
Calculating for 0
Calculating for 5
Calculating for 4 + 3
Calculating for 4
Calculating for 3 + 2
Calculating for 3
Calculating for 2 + 1
Calculating for 2
Calculating for 1 + 0
Calculating for 1
Calculating for 0
Calculating for 1
Calculating for 2
Calculating for 1 + 0
Calculating for 1
Calculating for 0
Calculating for 3
Calculating for 2 + 1
Calculating for 2
Calculating for 1 + 0
Calculating for 1
Calculating for 0
Calculating for 1
Out[38]: 13
In [39]: rec_fib(5000)
---------------------------------------------------------------------------
<ipython-input-39-978d0ba5a189> in <module>
----> 1 rec_fib(5000)
<ipython-input-36-92eee5791210> in rec_fib(num)
7 else:
10
11 rec_fib(0)
<ipython-input-36-92eee5791210> in rec_fib(num)
7 else:
10
11 rec_fib(0)
In [ ]:
In [ ]:
Lambda Expressions
https://docs.python.org/3.8/reference/expressions.html#lambda
add_vals_lambda(10,12)
Out[16]: 22
Out[17]: 62
In [19]: multiply_lambda(12,6,8)
Out[19]: 144
Out[43]: 55
In [ ]:
In [ ]:
Positional arguments are arguments that can be called by their position in the function
definition.
Keyword arguments are arguments that can be called by their name.
Required arguments are arguments that must passed to the function.
Optional arguments are argument that can need not passed to the function. In python
optional arguments are arguments that have a default value.
print('--------------------------')
p value is 1
q value is 2
r value is 3
s value is 4
--------------------------
p value is 12
q value is 23
r value is 65
s value is 1
--------------------------
p value is 23
q value is 1
r value is 65
s value is 12
--------------------------
p value is 12
q value is 15
r value is -2
s value is 36
--------------------------
In [23]: some_func(p = 12, 15, 36, r = -2 ) # Error because positional follows keyword
---------------------------------------------------------------------------
<ipython-input-24-664dd3852deb> in <module>
print('--------------------------')
a value is 12
b value is -2
c value is 50
d value is 20
--------------------------
a value is 12
b value is 55
c value is 50
d value is 20
--------------------------
In [28]: another_func(12)
---------------------------------------------------------------------------
<ipython-input-28-73d7f6be72db> in <module>
----> 1 another_func(12)
a value is 11
b value is -2
c value is 23
d value is 59
--------------------------
a value is 11
b value is -2
c value is Vivek
d value is 59
--------------------------
In [ ]:
Python Libraries
Libraries developed for most common tasks
Vast resources
Documented
Forked to create your own libraries
Others
Python Packages
https://pypi.org/
In [ ]:
Installing Libraries
using pip
Pandas
Master Pandas
https://pandas.pydata.org/docs/
In [46]: dir(pd)
Out[46]: ['BooleanDtype',
'Categorical',
'CategoricalDtype',
'CategoricalIndex',
'DataFrame',
'DateOffset',
'DatetimeIndex',
'DatetimeTZDtype',
'ExcelFile',
'ExcelWriter',
'Flags',
'Float32Dtype',
'Float64Dtype',
'Float64Index',
'Grouper',
'HDFStore',
'Index',
'IndexSlice',
'Int16Dtype',
'Int32Dtype',
'Int64Dtype',
'Int64Index',
'Int8Dtype',
'Interval',
'IntervalDtype',
'IntervalIndex',
'MultiIndex',
'NA',
'NaT',
'NamedAgg',
'Period',
'PeriodDtype',
'PeriodIndex',
'RangeIndex',
'Series',
'SparseDtype',
'StringDtype',
'Timedelta',
'TimedeltaIndex',
'Timestamp',
'UInt16Dtype',
'UInt32Dtype',
'UInt64Dtype',
'UInt64Index',
'UInt8Dtype',
'__builtins__',
'__cached__',
'__doc__',
'__docformat__',
'__file__',
'__getattr__',
'__git_version__',
'__loader__',
'__name__',
'__package__',
'__path__',
'__spec__',
'__version__',
'_config',
'_hashtable',
'_is_numpy_dev',
'_lib',
'_libs',
'_np_version_under1p17',
'_np_version_under1p18',
'_testing',
'_tslib',
'_typing',
'_version',
'api',
'array',
'arrays',
'bdate_range',
'compat',
'concat',
'core',
'crosstab',
'cut',
'date_range',
'describe_option',
'errors',
'eval',
'factorize',
'get_dummies',
'get_option',
'infer_freq',
'interval_range',
'io',
'isna',
'isnull',
'json_normalize',
'lreshape',
'melt',
'merge',
'merge_asof',
'merge_ordered',
'notna',
'notnull',
'offsets',
'option_context',
'options',
'pandas',
'period_range',
'pivot',
'pivot_table',
'plotting',
'qcut',
'read_clipboard',
'read_csv',
'read_excel',
'read_feather',
'read_fwf',
'read_gbq',
'read_hdf',
'read_html',
'read_json',
'read_orc',
'read_parquet',
'read_pickle',
'read_sas',
'read_spss',
'read_sql',
'read_sql_query',
'read_sql_table',
'read_stata',
'read_table',
'reset_option',
'set_eng_float_format',
'set_option',
'show_versions',
'test',
'testing',
'timedelta_range',
'to_datetime',
'to_numeric',
'to_pickle',
'to_timedelta',
'tseries',
'unique',
'util',
'value_counts',
'wide_to_long']
In [ ]:
Data Frames
Creating Data Frames using Lists
In [47]: number = []
square = []
number.append(i)
square.append(i**2)
number
In [48]: square
num_df
Out[49]: Number
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
In [50]: num_df2 = pd.DataFrame(number, index = square) # No column name, the square list passed
num_df2
Out[50]:
localhost:8888/nbconvert/html/Completed 004 2021-08-23 to 2021-09-10.ipynb?download=false 107/117
9/8/2021 Completed 004 2021-08-23 to 2021-09-10
1 1
4 2
9 3
16 4
25 5
36 6
49 7
64 8
81 9
100 10
In [ ]:
sq_list
(2, 4),
(3, 9),
(4, 16),
(5, 25),
(6, 36),
(7, 49),
(8, 64),
(9, 81),
(10, 100)]
sq_df
0 1 1
1 2 4
2 3 9
3 4 16
4 5 25
5 6 36
6 7 49
7 8 64
8 9 81
9 10 100
In [ ]:
In [ ]:
sq_dict
sq_df2
0 1 1
1 2 4
2 3 9
3 4 16
4 5 25
5 6 36
6 7 49
7 8 64
8 9 81
9 10 100
Read a File
image Source:
Data Source:
CSV file
read_csv
https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html
pokemon_df
VenusaurMega
3 Grass Poison 625 80 100 123 122 120 80 1 Fa
Venusaur
... ... ... ... ... ... ... ... ... ... ... ...
DiancieMega
796 Rock Fairy 700 50 160 110 160 110 110 6 T
Diancie
HoopaHoopa
797 Psychic Ghost 600 80 110 60 150 130 70 6 T
Confined
HoopaHoopa
798 Psychic Dark 680 80 160 60 170 130 80 6 T
Unbound
In [ ]:
pokemon_v2_df
Out[59]: 0 1 2 3 4 5 6 7 8 9 10 11
3 VenusaurMega Venusaur Grass Poison 625 80 100 123 122 120 80 1 False
... ... ... ... ... ... ... ... ... ... ... ... ...
795 Diancie Rock Fairy 600 50 100 150 100 150 50 6 True
796 DiancieMega Diancie Rock Fairy 700 50 160 110 160 110 110 6 True
797 HoopaHoopa Confined Psychic Ghost 600 80 110 60 150 130 70 6 True
798 HoopaHoopa Unbound Psychic Dark 680 80 160 60 170 130 80 6 True
Out[60]: 0 1 2 3 4 5 6 7 8 9 10 11
3 VenusaurMega Venusaur Grass Poison 625 80 100 123 122 120 80 1 False
... ... ... ... ... ... ... ... ... ... ... ... ...
0 1 2 3 4 5 6 7 8 9 10 11
In [ ]:
In [ ]:
pokemon_txt_df
VenusaurMega
3 Grass Poison 625 80 100 123 122 120 80 1 Fa
Venusaur
... ... ... ... ... ... ... ... ... ... ... ...
DiancieMega
796 Rock Fairy 700 50 160 110 160 110 110 6 T
Diancie
HoopaHoopa
797 Psychic Ghost 600 80 110 60 150 130 70 6 T
Confined
HoopaHoopa
798 Psychic Dark 680 80 160 60 170 130 80 6 T
Unbound
In [ ]:
In [ ]:
Excel File
read_excel
https://pandas.pydata.org/docs/reference/api/pandas.read_excel.html
pokemon_excel_df
VenusaurMega
3 Grass Poison 625 80 100 123 122 120 80 1 Fa
Venusaur
... ... ... ... ... ... ... ... ... ... ... ...
DiancieMega
796 Rock Fairy 700 50 160 110 160 110 110 6 T
Diancie
HoopaHoopa
797 Psychic Ghost 600 80 110 60 150 130 70 6 T
Confined
HoopaHoopa
798 Psychic Dark 680 80 160 60 170 130 80 6 T
Unbound
In [ ]:
In [ ]:
In [ ]:
Basic Operations
Exploring the Data
info
In [64]: pokemon_df.info()
<class 'pandas.core.frame.DataFrame'>
In [ ]:
shape
In [65]: pokemon_df.shape
describe
In [66]: pokemon_df.describe()
Out[66]: Total HP Attack Defense Sp. Atk Sp. Def Speed Generation
count 800 800 414 800.00000 800.000000 800.000000 800.000000 800.000000 800.000000 80
top Cleffa Water Flying NaN NaN NaN NaN NaN NaN
mean NaN NaN NaN 435.10250 69.258750 79.001250 73.842500 72.820000 71.902500 6
std NaN NaN NaN 119.96304 25.534669 32.457366 31.183501 32.722294 27.828916 2
min NaN NaN NaN 180.00000 1.000000 5.000000 5.000000 10.000000 20.000000
25% NaN NaN NaN 330.00000 50.000000 55.000000 50.000000 49.750000 50.000000 4
50% NaN NaN NaN 450.00000 65.000000 75.000000 70.000000 65.000000 70.000000 6
75% NaN NaN NaN 515.00000 80.000000 100.000000 90.000000 95.000000 90.000000 9
max NaN NaN NaN 780.00000 255.000000 190.000000 230.000000 194.000000 230.000000 18
Head
In [68]: pokemon_df.head()
VenusaurMega
3 Grass Poison 625 80 100 123 122 120 80 1 False
Venusaur
VenusaurMega
3 Grass Poison 625 80 100 123 122 120 80 1 Fals
Venusaur
CharizardMega
7 Fire Dragon 634 78 130 111 130 85 100 1 Fals
Charizard X
CharizardMega
8 Fire Flying 634 78 104 78 159 115 100 1 Fals
Charizard Y
BlastoiseMega
12 Water NaN 630 79 103 120 135 115 78 1 Fals
Blastoise
BeedrillMega
19 Bug Poison 495 65 150 40 15 80 145 1 Fals
Beedrill
In [ ]:
Tail
Zygarde50%
794 Dragon Ground 600 108 100 121 81 95 95 6 T
Forme
DiancieMega
796 Rock Fairy 700 50 160 110 160 110 110 6 T
Diancie
HoopaHoopa
797 Psychic Ghost 600 80 110 60 150 130 70 6 T
Confined
HoopaHoopa
798 Psychic Dark 680 80 160 60 170 130 80 6 T
Unbound
Column Names
In [71]: pokemon_df.columns
Out[71]: Index(['Name', 'Type 1', 'Type 2', 'Total', 'HP', 'Attack', 'Defense',
dtype='object')
In [72]: pokemon_df.columns.to_list()
Out[72]: ['Name',
'Type 1',
'Type 2',
'Total',
'HP',
'Attack',
'Defense',
'Sp. Atk',
'Sp. Def',
'Speed',
'Generation',
'Legendary']