In [ ]:
print 'Hello World'
In [ ]:
print ('Hello World')
In [ ]:
print("Hello World")
In [ ]:
import keyword
In [ ]:
print (keyword.kwlist)
In [ ]:
len(keyword.kwlist)
In [ ]:
a, b, _, _ = 1, 'potter', 23, 43
In [ ]:
a, b
In [ ]:
x, _, y, _ = 1, 2, 3, 4
In [ ]:
x, y
In [ ]:
a = b = c =2.17
In [ ]:
a,b,c
In [ ]:
# to get input from the user
user_input = raw_input("Give me some input!: ")
In [ ]:
A numpy array is a grid of values, all of the same type and is is indexed by a tuple of non-negative integers.
The number of dimensions is the RANK of the array.
The SHAPE of the array is a tuple of integers giving the size of the array along each dimension.
In [3]:
import numpy as np
In [21]:
a = np.array([1,2,3]) # creates RANK 1 array
In [22]:
a
Out[22]:
In [23]:
print(type(a))
In [24]:
print(a.shape)
In [25]:
print(a)
In [26]:
print(a[0], a[1], a[2])
In [27]:
a[0]
Out[27]:
In [28]:
a[1] = 123445
In [29]:
a
Out[29]:
In [15]:
print(a)
In [30]:
a[1] = 15
In [31]:
print(a)
In [32]:
b = np.array([[1, 2, 3], [4, 5, 6]])
In [33]:
print(b.shape)
In [34]:
print(b[0, 0])
In [36]:
print(b[1,2])
In [39]:
m_npZEROS = np.zeros((2,2))
In [42]:
m_npZEROS
Out[42]:
In [40]:
m_npONES = np.ones((3,3))
In [41]:
m_npONES
Out[41]:
In [54]:
m_npFULL = np.full((4,5), 17, dtype='int64')
In [55]:
m_npFULL
Out[55]:
In [60]:
m_npEYE = np.eye(3, 4)
In [61]:
m_npEYE
Out[61]:
In [62]:
m_npEYE = np.eye(3, 4, 1)
In [63]:
m_npEYE
Out[63]:
In [64]:
m_npEYE = np.eye(3, 4, -1)
In [65]:
m_npEYE
Out[65]:
In [74]:
m_npRANDOM = np.random.random((2,2))
m_npRANDOM
Out[74]:
In [ ]:
In [75]:
m_npRANDOM = np.random.random((2,2))
m_npRANDOM
Out[75]:
In [76]:
a = np.array([[1,2,3], [4,5,6], [7,8,9]])
In [78]:
b = a[:2, 1:3]
print(b)
A slice of the array is a view into the same data, so modifying the slice will also modify the original array
In [79]:
print(a[1,1])
In [81]:
print(b[1, 0])
b[1,0] = 100
print(b[1,0])
print(a[1,1])
In [82]:
a
Out[82]:
In [83]:
row_r1 = a[1, :]
row_r2 = a[1:2, :]
print(row_r1, row_r1.shape)
print(row_r2, row_r2.shape)
In [87]:
(np.eye(4)).shape
Out[87]:
In [88]:
a = [[1,2,3], [4,5,6]]
In [89]:
print(a)
In [96]:
b = a[1]
In [97]:
b
Out[97]:
In [98]:
b = a[:]
In [99]:
b
Out[99]:
In [100]:
b = [[10,20,30], [40,50,60]]
In [101]:
a
Out[101]:
In [102]:
b
Out[102]:
In [104]:
a = np.array([[1,2],[3,4],[5,6]])
print(a)
In [109]:
# integer array indexing
x = a[[0,1,2], [0,1,0]]
print(x)
print(x.shape)
In [112]:
# slicing
y = np.array([a[0,0], a[1,1], a[2,0]])
print(y)
print(y.shape)
In [113]:
# selcting/mutating one element from each row of a matrix
In [114]:
a = np.array([[1,2,3], [4,5,6], [7,8,9], [10,11,12]])
In [117]:
print(a)
print(a.shape)
In [118]:
b = np.array([1,2,0,1])
In [119]:
b
Out[119]:
In [120]:
print(a[np.arange(0,4), b])
In [121]:
print(a[np.arange(0,4), b])
In [125]:
a[np.arange(0,4),b] +=100
In [126]:
a
Out[126]:
Boolean array indexing lets us pick out arbitrary elements of an array.
This type of indexing is used to slect the elements of an array that satisfy some condition.
In [127]:
a = np.array([[1,2],[3,4],[5,6]])
In [128]:
bool_idx = (a>2)
In [129]:
bool_idx
Out[129]:
In [132]:
#boolean indexing: It produces a Rank 1 array
print(a[bool_idx])
In [133]:
print(a[a>3])
In [162]:
m_list = [1,2,3]
m_npARRAY = np.array([1,2,3])
In [163]:
for e in m_list:
print e
In [164]:
for e in m_npARRAY:
print e
In [165]:
m_list.append(4)
In [166]:
m_list
Out[166]:
In [167]:
m_npARRAY.append(4)
In [168]:
m_list += [5]
m_list
Out[168]:
In [169]:
m_npARRAY += [5]
m_npARRAY
Out[169]:
In [170]:
m_list += [6,7]
m_list
Out[170]:
In [171]:
m_npARRAY += [6,7]
In [172]:
m_npARRAY + m_npARRAY
Out[172]:
In [175]:
print m_npARRAY
print m_npARRAY * 2
In [176]:
print(m_list)
print(m_list * 2)
In [179]:
print(m_npARRAY)
print(m_npARRAY ** 2)
In [180]:
print(m_npARRAY)
print(np.sqrt(m_npARRAY))
In [181]:
print(m_list)
print(np.sqrt(m_list))
In [183]:
print(m_npARRAY)
print(np.log(m_npARRAY))
In [184]:
print(m_npARRAY)
print(np.exp(m_npARRAY))
In [185]:
a = np.array([1,21,32])
b = np.array([1,32,12])
In [192]:
dot = 0
In [193]:
for i,j in zip(a,b):
dot += i*j
In [194]:
print(dot)
In [195]:
a*b
Out[195]:
In [196]:
print(np.sum(a*b))
In [198]:
print((a*b).sum())
In [199]:
print(np.dot(a,b))
In [200]:
a.dot(b)
Out[200]:
In [201]:
b.dot(a)
Out[201]:
In [202]:
amag = np.sqrt((a*a).sum())
In [203]:
amag
Out[203]:
In [204]:
amag = np.linalg.norm(a)
In [205]:
amag
Out[205]:
In [208]:
cosAngle = a.dot(b)/(np.linalg.norm(a) * np.linalg.norm(b))
In [209]:
cosAngle
Out[209]:
In [210]:
angle = np.arccos(cosAngle) #in radians
In [211]:
angle
Out[211]:
In [217]:
# comparing numpy with default python functions
import numpy as np
from datetime import datetime
a = np.random.randn(100)
b = np.random.randn(100)
T = 100000
def slow_dot_product(a,b):
result = 0
for e,f in zip(a,b):
result += e*f
return result
t0 = datetime.now()
for t in xrange(T):
slow_dot_product(a,b)
dt1 = datetime.now() - t0
t0 = datetime.now()
for t in xrange(T):
a.dot(b)
dt2 = datetime.now() - t0
print("dt1/dt2 = ", dt1.total_seconds()/dt2.total_seconds())
In [218]:
z = np.zeros(10)
In [219]:
z
Out[219]:
In [222]:
z = np.zeros((10,10))
z
Out[222]:
In [223]:
o = np.ones(10)
o
Out[223]:
In [224]:
o = np.ones((10,10))
o
Out[224]:
In [228]:
g = np.random.randn(10,10)
g
Out[228]:
In [229]:
r = np.random.random((10,10))
r
Out[229]:
In [231]:
print(g.mean())
print(g.var())
In [232]:
print(r.mean())
print(r.var())
In [233]:
A = np.array([[1,2],[3,4]])
print(A)
In [234]:
Ainv = np.linalg.inv(A)
print(Ainv)
In [236]:
A.dot(Ainv)
Out[236]:
In [237]:
A*Ainv
Out[237]:
In [238]:
A.dot(A)
Out[238]:
In [239]:
np.linalg.det(A)
Out[239]:
In [240]:
np.linalg.det(Ainv)
Out[240]:
In [241]:
np.linalg.det(A.dot(Ainv))
Out[241]:
In [243]:
print(A)
np.diag(A)
Out[243]:
In [244]:
np.diag([1,2])
Out[244]:
In [245]:
np.diag([1,2,3])
Out[245]:
In [246]:
a = np.array([1,2])
b = np.array([3,4])
In [247]:
print(np.outer(a,b))
print(np.inner(a,b))
print(a.dot(b))
In [248]:
np.diag(A).sum()
Out[248]:
In [249]:
np.trace(A)
Out[249]:
In [250]:
x = np.random.randn(100,3)
In [251]:
x
Out[251]:
In [252]:
cov = np.cov(x)
cov
Out[252]:
In [253]:
cov.shape
Out[253]:
In [254]:
cov = np.cov(x.T)
In [255]:
cov
Out[255]:
In [256]:
cov.shape
Out[256]:
In [257]:
np.linalg.eigh(cov)
Out[257]:
In [258]:
np.linalg.eig(cov)
Out[258]:
In [260]:
#linear system
# Ax = b
#=> A-1.A.x = 0
#=> x = A-1.b
In [261]:
A
Out[261]:
In [262]:
b
Out[262]:
In [263]:
b = np.array([1,2])
In [264]:
b
Out[264]:
In [265]:
x = np.linalg.inv(A).dot(b)
print(x)
In [267]:
x = np.linalg.solve(A,b)
print(x)
In [268]:
A = np.array([[1,1],[1.5,4]])
b = np.array([2200,5050])
x = np.linalg.solve(A,b)
print(x)
In [271]:
Y = []
Y
Out[271]:
In [278]:
Y = []
for line in open("data_2d.csv"):
row = line.split(',')
sample = map(float, row)
Y.append(sample)
Y = np.array(Y)
print(Y)
In [279]:
Y.shape
Out[279]:
In [281]:
import matplotlib.pyplot as plt
In [284]:
import pandas as pd
In [1]:
import pandas as pd
In [2]:
pd.show_versions()
In [1]:
import pandas as pd
In [2]:
Y = pd.read_csv("data_2d.csv", header=None)
In [3]:
Y
Out[3]:
In [4]:
type(Y)
Out[4]:
In [5]:
Y.info()
In [6]:
Y.head()
Out[6]:
In [7]:
Y.head(9)
Out[7]:
In [8]:
Y[0]
Out[8]:
In [9]:
type(Y[0])
Out[9]:
In [10]:
Y.iloc[0]
Out[10]:
In [12]:
Y.ix[0]
Out[12]:
In [13]:
Y[[0,2]]
Out[13]:
In [14]:
Y[ Y[0] < 5 ]
Out[14]:
In [15]:
Y[0] < 5
Out[15]:
In [16]:
type(Y[0] < 5)
Out[16]:
In [17]:
df = pd.read_csv("international-airline-passengers.csv", engine="python", skipfooter=3)
In [18]:
df
Out[18]:
In [20]:
df.columns
Out[20]:
In [21]:
df.columns = ['month', 'passangers']
In [22]:
df.columns
Out[22]:
In [23]:
df
Out[23]:
In [25]:
df['passangers']
Out[25]:
In [27]:
df.passangers
Out[27]:
In [28]:
df['ones'] = 1
In [29]:
df.head()
Out[29]:
In [34]:
from datetime import datetime
datetime.strptime("2018-05", "%Y-%m")
df['x1x2'] = df.apply(lambda row: datetime.strptime(row["month"], "%Y-%m"), axis=1)
In [35]:
df.head()
Out[35]:
In [36]:
df.info()
In [38]:
t1 = pd.read_csv("table1.csv")
t2 = pd.read_csv("table2.csv")
In [39]:
t1
Out[39]:
In [40]:
t2
Out[40]:
In [41]:
type(t1)
Out[41]:
In [44]:
m = pd.merge(t1,t2,on='user_id')
In [45]:
m
Out[45]:
In [46]:
t1.merge(t2, on="user_id")
Out[46]:
In [50]:
import numpy as np
import matplotlib.pyplot as plt
In [82]:
x = np.linspace(0,10,100)
y = np.sin(x)
plt.plot(x,y)
plt.xlabel('time')
plt.ylabel('sine')
plt.title('Cool function')
plt.show()
In [83]:
import pandas as pd
d1 = pd.read_csv("data_1d.csv").as_matrix()
In [84]:
x1 = d1[:,0]
y1 = d1[:,1]
In [85]:
plt.scatter(x1,y1)
plt.show()
In [86]:
x_line = np.linspace(0,100,100)
y_line = 2*x_line + 1
plt.scatter(x1, y1)
plt.plot(x_line, y_line)
plt.show()
In [90]:
plt.hist(x1)
plt.show()
In [92]:
plt.hist(y1)
plt.show()
In [94]:
plt.hist2d(x1,y1)
plt.show()
In [96]:
R = np.random.random(10000)
plt.hist(R)
plt.show()
In [97]:
plt.hist(R, bins=20)
plt.show()
In [98]:
y_actual = 2*x1 + 1
res = y1 - y_actual
plt.hist(res)
plt.show()
In [1]:
import numpy as np
In [2]:
r = np.random.randn(10000, 2)
In [3]:
import matplotlib.pyplot as plt
In [4]:
plt.scatter(r[:,0], r[:,1])
plt.show()
In [5]:
r[:,1] = 5*r[:,1] + 2
In [7]:
plt.scatter(r[:,0], r[:,1])
plt.axis('equal')
plt.show()
In [8]:
cov = np.array([[1, 0.8], [0.8, 3]])
In [9]:
from scipy.stats import multivariate_normal as mvn
In [10]:
mu = np.array([0,2])
mu
Out[10]:
In [11]:
r = mvn.rvs(mean = mu, cov=cov, size=1000)
In [25]:
plt.scatter(r[:,0], r[:,1])
plt.axis('equal')
plt.show()
In [26]:
r = np.random.multivariate_normal(mean = mu, cov=cov, size=1000)
plt.scatter(r[:,0], r[:,1])
plt.axis('equal')
plt.show()
In [28]:
x = np.linspace(0, 100, 10000)
y = np.sin(x) + np.sin(3*x) + np.sin(5*x)
plt.plot(y)
plt.show()
In [30]:
Y = np.fft.fft(y)
plt.plot(np.abs(Y))
plt.show()
In [1]:
s = """w'o"w"""
In [2]:
repr(s)
Out[2]:
In [3]:
str(s)
Out[3]:
In [5]:
eval(str(s)) == s
In [6]:
eval(repr(s)) == s
Out[6]:
In [7]:
eval(repr(s))
Out[7]:
In [8]:
s
Out[8]:
In [9]:
str(s)
Out[9]:
In [10]:
eval(str(s))
In [12]:
type(str(s))
Out[12]:
In [13]:
type(repr(s))
Out[13]:
In [14]:
type(s)
Out[14]:
In [15]:
import datetime
In [16]:
today = datetime.datetime.now()
In [17]:
str(today)
Out[17]:
In [18]:
repr(today)
Out[18]:
In [19]:
eval(str(today)) == eval(repr(today))
In [20]:
# when writing a class we can override these methods
# to do whatever we want:
In [40]:
class Represent(object):
def __init__(self,x,y):
self.x, self.y = x,y
def __repr__(self):
return "Represent(x={}, y=\"{}\")".format(self.x, self.y)
def __str__(self):
return "Representing x as {} and y as {}".format(self.x, self.y)
In [41]:
r = Represent(1, "Rustom")
In [42]:
print(r)
In [43]:
print(r.__repr__)
In [44]:
rep = r.__repr__()
In [45]:
print(rep)
In [46]:
r2 = eval(rep)
In [47]:
print(r2)
In [49]:
type(r)
Out[49]:
In [50]:
type(r2)
Out[50]:
In [51]:
print(r2 == r)
In [53]:
rep
Out[53]:
In [8]:
# sets: mutable unordered collection of unique objects
In [9]:
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
In [10]:
print(basket)
In [11]:
a = set('abrakadabra')
In [12]:
a
Out[12]:
In [13]:
a.add('z')
In [14]:
a
Out[14]:
In [15]:
# frozen sets: non-mutable sets
In [16]:
b = frozenset('dbdfhbsdjfjsbd')
In [17]:
print(b)
In [18]:
b
Out[18]:
In [35]:
cities = frozenset({"calcutta", 'delhi', 'bangalore', 'delhi'})
In [36]:
cities
Out[36]:
In [21]:
# number data types:
In [31]:
int_num = 10
print(int_num, type(int_num))
In [32]:
float_num = 10.2
print(float_num, type(float_num))
In [33]:
complex_num = 2+3.14j
print(complex_num, type(complex_num))
In [34]:
long_num = 123456L
print(long_num, type(long_num))
In [37]:
# operations on sets
In [39]:
a = {1,2,3,4,5}
b = {3,4,5,6}
# intersection
print(a.intersection(b))
print(a & b)
#union
print(a.union(b))
print(a | b)
# difference
print(a.difference(b))
print(a - b)
# symmetric difference
print(a.symmetric_difference(b))
print(a ^ b)
# superset check
print(a.issuperset(b))
print(a >= b)
# subset check
print(a.issubset(b))
print(a <= b)
# disjoint check
print(a.isdisjoint(b))
In [40]:
2 in {1,2,3,4}
Out[40]:
In [41]:
4 not in {1,2,34,5}
Out[41]:
In [42]:
a.add(12545)
In [43]:
a
Out[43]:
In [44]:
a.remove(1)
In [45]:
a
Out[45]:
In [46]:
a.discard(1)
In [47]:
a
Out[47]:
In [48]:
b
Out[48]:
In [49]:
a.difference(b)
Out[49]:
In [50]:
a.symmetric_difference(b)
Out[50]:
In [53]:
restaurants = ['Swiggy', 'Aaha Andhra', 'Sri Sagar', 'Swiggy', 'Swiggy', 'Sri Sagar']
print(restaurants)
print('Unique restaurants as set(): ', set(restaurants))
print('Unique restaurants as list()', list(set(restaurants)))
In [54]:
set(restaurants)
Out[54]:
In [56]:
list(set(restaurants))
Out[56]:
In [57]:
unique_restro = set(restaurants)
In [58]:
unique_restro
Out[58]:
In [59]:
list(unique_restro)
Out[59]:
In [60]:
{{1,2}, {3,4}}
In [62]:
x=1
y=2
In [63]:
{x,y}
Out[63]:
In [64]:
x=5
In [65]:
{x,y}
Out[65]:
In [66]:
{x,y}
Out[66]:
In [67]:
x
y
Out[67]:
In [68]:
x
Out[68]:
In [69]:
y
Out[69]:
In [70]:
a
Out[70]:
In [71]:
b
Out[71]:
In [72]:
a - b
Out[72]:
In [73]:
b - a
Out[73]:
In [74]:
a.symmetric_difference(b)
Out[74]:
In [75]:
b.symmetric_difference(a)
Out[75]:
In [76]:
from collections import Counter
In [77]:
counterA = Counter(['a','b','a','b','c'])
In [78]:
counterA
Out[78]:
In [1]:
squares = [x*x for x in (1,2,3,4,5,6)]
print(squares)
In [2]:
[s.upper() for s in "Rustom Potter"]
Out[2]:
In [9]:
[w.strip(',') for w in ['nsd,,,',',,,fjg','nsdj,fb,jb,df',',,bjdfb,,,hbsd','ndj,,,fbsj,,,']]
Out[9]:
In [13]:
sentence = "Beautiful is better than ugly"
["".join(sorted(word, key = lambda x: x.lower())) for word in sentence.split()]
In [14]:
[x for x in 'apple' if x in 'aeiou']
Out[14]:
In [15]:
[x for x in 'apple' if x in 'aeiou' else '*']
In [16]:
[x if x in 'aeiou' else '*' for x in 'apple']
Out[16]:
In [1]:
'spam'
Out[1]:
In [2]:
2**100
Out[2]:
In [3]:
len(str(2**100000))
Out[3]:
In [4]:
3.1415**2
Out[4]:
In [5]:
3.1415*2
Out[5]:
In [6]:
print(3.1415*2)
In [7]:
import math
print(math.pi)
print(math.sqrt(89))
In [9]:
import random
print(random.random())
print(random.choice([1,2,3,4,43]))
In [13]:
S = 'rustomPotter'
In [14]:
L = list(S)
In [15]:
L
Out[15]:
In [16]:
L[1] = '217'
In [17]:
L
Out[17]:
In [18]:
''.join(L)
Out[18]:
In [19]:
B = bytearray('rustomPotter')
In [20]:
B
Out[20]:
In [21]:
B.extend('217')
In [22]:
B
Out[22]:
In [23]:
B.capitalize()
Out[23]:
In [24]:
B.decode()
Out[24]:
In [34]:
B2 = bytearray('roadster')
B2
Out[34]:
In [35]:
B2.append('T')
In [36]:
B2
Out[36]:
In [37]:
B2.extend('esla')
In [38]:
B2
Out[38]:
In [39]:
B2.decode()
Out[39]:
In [1]:
'%s, spam and %s' % ('spam', 'SPAM!')
Out[1]:
In [4]:
'{0}, eggs and {1}'.format('spam', 'SPAM!')
Out[4]:
In [5]:
'{1}, eggs and {0}'.format('spam', 'SPAM!')
Out[5]:
In [6]:
'{}, eggs and {}'.format('spam', 'SPAM!!!!')
Out[6]:
In [7]:
'{:,.2f}'.format(125646546.4154541)
Out[7]:
In [12]:
'%.2f and %+05d' % (4561.1545, -54)
Out[12]:
In [ ]:
dir()
In [9]:
while True:
reply = input("Enter:")
if reply == "stop": break
print(int(reply)**2)
In [10]:
range(3)
Out[10]:
In [11]:
list(range(3))
Out[11]:
In [12]:
a, *b = range(100)
In [13]:
type(2>3)
Out[13]:
In [14]:
True
Out[14]:
In [4]:
a=0
b=10
while a<b:
print(a)
a += 1
In [5]:
x = ...
In [11]:
list(range(-5, -15, -1))
Out[11]:
In [12]:
s = "abcdefghijklmnopqrstuvwxyz"
In [16]:
for i in xrange(0, len(s), 2):
print s[i]
In [15]:
for i in s[::2]:
print i
In [17]:
L1 = [1,2,3,4,5,6]
L2 = [7,8,9,10,11,12]
for (x,y) in zip(L1, L2):
print x,y,'--', x+y
In [18]:
map(ord, 'spam')
Out[18]:
In [19]:
ord
Out[19]:
In [1]:
f = open('pythonNotes.py')
f.next()
Out[1]:
In [2]:
f.next()
Out[2]:
In [5]:
next(f)
Out[5]:
In [11]:
for line in open('tensorflow1.py'):
print line,
In [12]:
import sys
print sys.path
In [13]:
L = [1,2,3,4,5]
In [15]:
I = iter(L)
In [16]:
I
Out[16]:
In [17]:
I.next()
Out[17]:
In [1]:
M = map(lambda x:x**2, range(7))
print M
In [2]:
print M
In [4]:
for i in M:
print i
for i in M:
print i
In [5]:
for i in M:
print i
In [6]:
xrange(5)
Out[6]:
In [7]:
range(5)
Out[7]:
In [9]:
m_iterXrange = iter(xrange(5))
In [10]:
next(m_iterXrange)
Out[10]:
In [11]:
next(m_iterXrange)
Out[11]:
In [12]:
m_iterXrange.next()
Out[12]:
In [15]:
help(int)
In [16]:
help("")
In [17]:
help()
In [19]:
D={1:11, 2:22, 3:33, 4:44, 5:55}
In [20]:
print D
In [22]:
for k in D.keys().sort():
print k
In [ ]: