Python Basics 1689905586
Python Basics 1689905586
1. Lists
In [11]:
## Empty list
my_list = []
print(my_list)
## Pre-initialized list
height = [1,2,3, "Rohit"]
print(height)
[]
[1, 2, 3, 'Rohit']
Size of Container
In [12]:
d1 = {1:'Apple',2:'Google',3:'IBM'}
print('Lenth of dictionary =',len(d1))
Length of list1 = 5
Lenth of dictionary = 3
## R uses class()
## Python uses type()
x = 'Rohit'
y = '2017'
z = 2017
print(type(x),type(y),type(z))
In [18]:
Out[18]:
50
In [19]:
a = [1,2,3]
b = a
b[1] = 99
print(a)
[1, 99, 3]
Mutable vs Immutable
Mutable objects allow partial edits. List, Dictionary, Set
Immutable objects can be considered static/constant. You cannot make partial edits. Numeric, Boolean,
String, Tuple
In [20]:
## Mutable objects
my_list = [2,5,6,7]
print(my_list)
my_list[2] = 99
print(my_list)
[2, 5, 6, 7]
[2, 5, 99, 7]
In [23]:
## Immutable objects
my_tuple = (2,5,6,7)
print(my_tuple)
my_tuple[2] = 99
print(my_tuple)
(2, 5, 6, 7)
--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
<ipython-input-23-05d84a750e0a> in <module>()
3 print(my_tuple)
4
----> 5 my_tuple[2] = 99
6 print(my_tuple)
In [24]:
Rohit 1590240243360
Saigal 1590240888568
In [9]:
## Behavious
Apple = 20
Orange = Apple
print("Apple",Apple,id(Apple))
print("Orange",Orange,id(Orange))
Apple 20 1980788800
Orange 20 1980788800
In [35]:
Banana = Banana + 5
print("Banana",Banana,id(Banana))
print("Mango",Mango,id(Mango))
Banana 20 1463382080
Mango 20 1463382080
Banana 25 1463382240
Mango 20 1463382080
In [28]:
Fruits[3] = 99
print("Fruits",Fruits,id(Fruits))
print("Veggies",Veggies,id(Veggies))
Generating a sequence
In [30]:
## Custom sequence from specific start and end points with variable leap
sequence3 = list(range(100,150,10))
print('sequence3 =',sequence3)
sequence1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19]
sequence2 = [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]
sequence3 = [100, 110, 120, 130, 140]
In [42]:
[0, 1, 2, 3, 4]
[2, 3]
[2, 3, 4]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
In [31]:
## Negative Slicing
nums = list(range(5))
print(nums[-1:]) # Last 2 elements "[3,4]"
print(nums[:-1]) # All elements from starting till second to last (Excluding l
ast element) "[0, 1, 2, 3]"
[4]
[0, 1, 2, 3]
In [32]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 5, 8]
[0, 3, 6]
[5, 7, 9]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[5, 4, 3, 2, 1, 0]
[7, 5, 3]
In [17]:
## List functions
l1 = list(range(10))
l1[1] = 99 # Updating a value at particular index
print(l1)
[0, 99, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 99, 2, 3, 4, 55, 66, 77, 7, 8, 9]
[0, 99, 2, 3, 4, 55, 66, 77, 7, 8, 9, 777]
[0, 99, 2, 3, 4, 55, 66, 77, 7, 8, 9, 777, 111, 222, 333]
11
[0, 99, 2, 3, 4, 55, 66, 77, 7, 8, 9, 111, 222, 333]
Iterating in a Container
In [33]:
cat
dog
monkey
In [34]:
Index 1: cat
Index 2: dog
Index 3: monkey
In [35]:
In [37]:
In [38]:
[0, 4, 16]
Dictionaries
Keys and Values
In [41]:
d = {'cat': 'cute', 'dog': 'furry'} # Create a new dictionary with some data
print(d)
cute
True
{'cat': 'cute', 'dog': 'furry', 'fish': 'wet'}
In [64]:
person
cat
spider
2
4
8
In [42]:
for key, value in d.items(): # dictionary.items() will give you key valu
e pairs
print('A %s has %d legs' % (key, value))
In [45]:
0 is even
5 is odd
10 is even
15 is odd
20 is even
25 is odd
30 is even
35 is odd
40 is even
45 is odd
50 is even
55 is odd
60 is even
65 is odd
70 is even
75 is odd
80 is even
85 is odd
90 is even
95 is odd
100 is even
In [46]:
i = 1
while i < 10:
print(i)
i += 1
1
2
3
4
5
6
7
8
9
In [10]:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
1
2
3
In [47]:
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
1
2
4
5
6
In [49]:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
1
2
3
4
5
i is no longer less than 6
In [51]:
In [54]:
side = 4
print(areaSquare(9))
81
In [55]:
class ComplexNumber:
def __init__(self,r = 0,i = 0):
self.real = r
self.imag = i
def getData(self):
print("{0}+{1}j".format(self.real,self.imag))
In [17]:
2+3j
(5, 0, 10)
In [59]:
class Vehicle:
def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_veloci
ty):
self.number_of_wheels = number_of_wheels
self.type_of_tank = type_of_tank
self.seating_capacity = seating_capacity
self.maximum_velocity = maximum_velocity
def number_of_wheels(self):
return self.__number_of_wheels
In [60]:
In [61]:
print(tesla_model_s.number_of_wheels)
In [62]:
In [ ]:
## https://medium.com/the-renaissance-developer/learning-python-from-zero-to-hero-8ceed
48486d5
In [ ]:
Pandas DataFrame
In [28]:
# import pandas
import pandas as pd
In [30]:
(577, 18)
Index(['id', 'season', 'city', 'date', 'team1', 'team2', 'toss_winner',
'toss_decision', 'result', 'dl_applied', 'winner', 'win_by_runs',
'win_by_wickets', 'player_of_match', 'venue', 'umpire1', 'umpire2',
'umpire3'],
dtype='object')
RangeIndex(start=0, stop=577, step=1)
id int64
season int64
city object
date object
team1 object
team2 object
toss_winner object
toss_decision object
result object
dl_applied int64
winner object
win_by_runs int64
win_by_wickets int64
player_of_match object
venue object
umpire1 object
umpire2 object
umpire3 float64
dtype: object
In [32]:
df.head(2)
Out[32]:
Chennai
2008- Kings XI Chennai
1 2 2008 Chandigarh Super bat normal
04-19 Punjab Super Kings
Kings
In [34]:
df.tail(10)
Out[34]:
Kolkata
2016- Gujarat Gujarat
567 568 2016 Kanpur Knight field
05-19 Lions Lions
Riders
Kolkata
2016- Sunrisers Sunrisers
571 572 2016 Kolkata Knight field
05-22 Hyderabad Hyderabad
Riders
Royal Royal
2016- Delhi
572 573 2016 Raipur Challengers Challengers field
05-22 Daredevils
Bangalore Bangalore
Royal Royal
2016- Gujarat
573 574 2016 Bangalore Challengers Challengers field
05-24 Lions
Bangalore Bangalore
Kolkata Kolkata
2016- Sunrisers
574 575 2016 Delhi Knight Knight field
05-25 Hyderabad
Riders Riders
Royal
2016- Sunrisers Sunrisers
576 577 2016 Bangalore Challengers bat
05-29 Hyderabad Hyderabad
Bangalore
Subsetting DataFrames
In [38]:
Out[38]:
In [44]:
df[df['season'].isin([2008,2015])][['season','toss_winner']].tail(10)
Out[44]:
season toss_winner
In [47]:
Mumbai Indians 80
Chennai Super Kings 79
Royal Challengers Bangalore 70
Kolkata Knight Riders 68
Kings XI Punjab 63
Rajasthan Royals 63
Delhi Daredevils 56
Sunrisers Hyderabad 34
Deccan Chargers 29
Pune Warriors 12
Name: winner, dtype: int64
In [50]:
In [51]:
# The set_index() function is used to set the DataFrame index using existing columns
df.set_index('date',inplace=True) # Setting date column as index
Indexing
1. loc (Row/Column labels)
2. iloc (Row/Column index)
3. ix (Mixed mode - Depricated)
In [52]:
## loc
print(df.loc[['2008-04-18','2008-04-26'],'city'])
date
2008-04-18 Bangalore
2008-04-26 Bangalore
2008-04-26 Chennai
Name: city, dtype: object
In [53]:
# loc gets rows (or columns) with particular labels from the index
df.loc['2008-04-18':'2008-04-21',['team1','team2']]
Out[53]:
team1 team2
date
In [54]:
Out[54]:
date
2008-04- Delhi
Delhi Rajasthan Royals Rajasthan Royals bat
19 Daredevils
Missing Values
In [56]:
team2
date
2014-04-19 Royal Challengers Bangalore
2014-04-19 Delhi Daredevils
2014-04-23 Rajasthan Royals
2014-04-25 Delhi Daredevils
2014-04-25 Chennai Super Kings
2014-04-28 Kings XI Punjab
2014-04-30 Mumbai Indians
Imputation
In [57]:
#new_df = df.copy
#new_df['city'].fillna('bfill')('ffill)
df['city'].fillna(method='bfill',inplace=True)
print(df[nas_list].iloc[:,1:5])
team2
date
2014-04-19 Royal Challengers Bangalore
2014-04-19 Delhi Daredevils
2014-04-23 Rajasthan Royals
2014-04-25 Delhi Daredevils
2014-04-25 Chennai Super Kings
2014-04-28 Kings XI Punjab
2014-04-30 Mumbai Indians
In [58]:
Out[58]:
date
Creating DataFrames
In [60]:
dict1 = {'metal':['steel','copper','wood'],'YM':[200,100,50],'Ductile':[True,True,False
]}
df1=pd.DataFrame(dict1,index=['m1','m2','m3'])
df1
Out[60]:
Ductile YM metal
m3 False 50 wood
DataFrame Transpose
In [61]:
df1.transpose()
Out[61]:
m1 m2 m3
YM 200 100 50
Adding row/column
file:///C:/Users/Geethika Reddy/Downloads/Basic_python_lyst9955 (1).html 20/26
7/20/2020 Basic@python
In [62]:
df1.loc['m4',:] = ['False',0.1,'cement']
df1
Out[62]:
Ductile YM metal
Dropping row/column
In [63]:
print(df1.drop('metal',axis=1))
print(df1.drop('m4',axis=0))
Ductile YM
m1 True 200.0
m2 True 100.0
m3 False 50.0
m4 False 0.1
Ductile YM metal
m1 True 200.0 steel
m2 True 100.0 copper
m3 False 50.0 wood
Appending DataFrame
In [64]:
dict2 = {'metal':['aluminium','bronze'],'YM':[180.2,102.1],'Ductile':[True,False]}
df2 = pd.DataFrame(dict2,index=['m4','m5'])
print(df1.append(df2))
Ductile YM metal
m1 True 200.0 steel
m2 True 100.0 copper
m3 False 50.0 wood
m4 False 0.1 cement
m4 True 180.2 aluminium
m5 False 102.1 bronze
Merging dataframes
In [65]:
Out[65]:
me3 40 5 wood
In [67]:
## merge df1 df3 on metal outer right and left index true
pd.merge(df1,df3,on='metal',how='right')
Out[67]:
Numpy Definition: a Python library used for scientific computing. It can also be
used as an efficient multi-dimensional container for data.
In [2]:
In [3]:
python_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print((python_list) * 2)
print(type(python_list))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]
<class 'list'>
In [8]:
[ 2 4 6 8 10 12 14 16 18]
<class 'numpy.ndarray'>
int32
In [6]:
print(python_list + python_list)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [9]:
print(numpy_array + numpy_array)
[ 2 4 6 8 10 12 14 16 18]
In [10]:
# Size of an array
numpy_array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
print(numpy_array.size)
In [11]:
(2, 4)
In [31]:
# Reshaping an array
numpy_matrix = np.array([(1, 2, 3, 4), (5, 6, 7, 8)])
numpy_matrix = numpy_matrix.reshape(4, 2)
print(numpy_matrix)
[[1 2]
[3 4]
[5 6]
[7 8]]
In [14]:
In [16]:
[1 2 3 4]
In [17]:
[9 8 7 6 5 4 3 2 1]
In [18]:
9
1
45
In [43]:
5.0
5.0
6.666666666666667
2.581988897471611
In [19]:
[[1 2 3 4]
[5 6 7 8]]
Sum of y-axis [ 6 8 10 12]
Sum of x-axis [10 26]
Overall Sum 36
In [20]:
[1 2 3 4 5 6 7 8 9]
In [21]:
array_4 = np.array([[1,2,3],[0,0,0]])
array_5 = np.array([[0,0,0],[7,8,9]])
print(np.concatenate((array_4, array_5), axis = 0))
[[1 2 3]
[0 0 0]
[0 0 0]
[7 8 9]]
In [52]:
[[0. 0.]]
[[0 0]]
[[1. 1.]]
[[1 1]]
In [24]:
[[1. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0.]
[0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 1. 0.]
[0. 0. 0. 0. 0. 1.]]
In [55]:
# Creating 8 x 7 matrix with first upper diagonal shifted one over denoted with k = 1
print(np.eye(8, 7, k = 1))
[[0. 1. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0.]
[0. 0. 0. 1. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 0. 1. 0.]
[0. 0. 0. 0. 0. 0. 1.]
[0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0.]]
In [26]:
# Multiplying matrices
array_6 = np.array([ 1, 2 ])
array_7 = np.array([ 3, 4 ])
print(np.dot(array_6, array_7))
11
In [ ]: