Please refer to python 3 documentation
import numpy as np
# Creating two lists, a and b
a=[1,2,3]
b=[4,5,6]
c=np.concatenate((a,b))
print(c)
## Logial operations are element-wise ##
# Create an array
f = np.array([1,2,3,4,5])
print('This is the frist output: ',f < 4)
print('This is the second output: ',(f<4) | (f>4)) # | is logical symbol for 'or'
## Sums and Averages of elements inside array##
g = np.array([[1,2,3],[4,5,6]])
print(g)
g.sum()
g.sum(axis=1)
g.mean()
g.std()
# If we are not sure what a function or object is, then
# we can look to the help page.
help(g.std)
g.std(axis=1)
# Take two matrices, a and b, then concatenate them.
a=np.array([[1,2,3],[4,5,6]])
b=np.array([[1,2,3],[7,8,9]])
c=np.concatenate((a,b))
print(c)
d = np.transpose(c) # transpose of c
f = d[:,0:3] # first 3 columns of d
g = np.eye(3) # identity 3x3
h = np.concatenate((f,g), axis=0) # linking f and g
I = np.concatenate((f,g), axis=1) # linking f and g
print(I) # axis=1
# Lets use sympy to construct a matrix
## Matrices from docs.sympy.org ##
from sympy import *
# We can also make the output look pretty
init_printing(use_unicode=True)
M = Matrix([[1,2,3],[4,5,6],[7,8,9]])
print('Row Reduce Echelon Form of the Matrix M is:\n')
M.rref()
print("See, we can still print, but it doesn't look as nice\n",M)
A = Matrix([[1,2,3],[4,5,6],[7,8,9]])
# If you need an immutable version of Matrix, use ImmutableMatrix
A.shape
# to get individual rows of columns, use:
A.row(0)
A.col(1)
# deleting and inserting rows and columns
A.row_del(1)
A
A.T
A = Matrix([[2,3,4],[5,8,3],[3,3,3]])
A
A.rref() # (rref, pivot columns)
A.nullspace()
B = Matrix([[1,2,3],[4,5,6],[7,8,9]])
B
B.rref()
B.nullspace()
## Eigenvalues and Eigenvectors ##
A.eigenvals() # returns (eigenvalue:algebraic multiplicity)
A.eigenvects()
# which returns (eigenvalue:algebraic multiplicity, [eigenvectors])
## dagonlizable matrices ##
# A = PDP^-1
P, D = A.diagonalize()
print(P)
print(D)
# remember that lambda is a reserved keyword in python, so
# to create the symbol use: lamda (without the 'b')
lamda = symbols('lamda')
B = Matrix([[1, 0 , 1],[1, 1, 2], [ 1, 0, 1]])
B
b = B.charpoly(lamda)
b
factor(b)
x = symbols('x')
y = x**2 + 5*x + 6
print(y)
y_x = integrate(y)
pprint(y_x)
## Constructing a large lil_matrix and add values to it ##
from scipy.sparse import lil_matrix
from scipy.sparse.linalg import spsolve
from numpy.linalg import solve, norm
from numpy.random import rand
## Optimization ##
#Minimization (steepest-decentm conjugate gradient), curve-fitting, least squares, root finding (Newton's method), annealing, etc.
import scipy.optimize as optimize
## Curve Fitting Example ##
def func(x,a,b,c):
return a*np.exp(-b*x) + c
x = np.linspace(0,4,50) # 50 values linearly in [0,4]
y = func(x,2.5,1.3,0.5)
yn = y + 0.2*np.random.normal(size=len(x))
popt,pcov = optimize.curve_fit(func,x,yn)
popt,pcov # optimized parameters and their covariance
## Matplotlib ##
from matplotlib.pyplot import *
from pylab import *
x = np.arange(0,10,0.2)
y = np.cos(x)
figure()
plot(x,y,'g*')
show()
# or we can show the figure inline
%matplotlib inline
plot(x,-np.exp(2*y),'g*')
## Contidtionsl and Flow Statements ##
## 'if' Statement
x = int(1) # Change the initial condition to alt output
if x < 0:
x = 0
print('Negative goes to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('single')
else:
print('More')
## Examples using 'for' statement
# create a list of names
Names = ['Rob', 'Ron', 'Felish', 'George', 'Shoe']
for x in Names:
# print the ith element of the list, followed by
# the number of charecters the name has.
print(x, len(x))
# Here's another way to do the same thing...
# but let x be the ith iteration.
Names = ['Rob', 'Ron', 'Felish', 'George', 'Shoe']
for i in range(len(Names)):
print(i,Names[i])
for x in range(5): # range(5) = {0,1,2,3,4}
if x == 3: # if x=3, print out the string
print('Three')
elif x == 0: # "elseif" needed after 'if' to continue with condiditions of the same statement
print('Zero')
else: # otherwise, print out the remaining
print(x)
for x in Names[:]: # Loops over a slice copy of the entire list.
if len(x) > 5:
Names.remove(x)
Names.append('Name')
Names
## 'break' and 'continue' Statements, and 'else' Clauses on loops
## Prime Numbers ##
for n in range(2,50):
for x in range(2, n):
if n % x == 0:
print(n, '=', x, '*', n/x)
break
else:
# loop fell through without finding a factor
print(n, 'is a prime number')
## Even and Odd example
for n in range(2, 10):
if n % 2 == 0:
print('Found an even number', n)
continue
print('Found an odd number', n)
## 'pass' Statements
# pass statement does nothin. It can be used requires no action.
# It can be used for creaing minimal classes.
# It can also be used as a place-holder for a function
def initlog(*arguments):
pass # remember to implement this!
## Defining Functions ##
def fib(n): # write Fibonacci series up to n
"""Print a Fibonacci series up to n."""
a,b = 0,1
while a < n:
print(a,)
a,b = b,a+b
# Now, calling on the function just made
fib(2000)
## changing fib to fib2
def fib2(n): # write Fibonacci series up to n
"""Return a list containing the Fibonacci series up to n."""
result = []
a,b = 0,1
while a < n:
result.append(a)
a,b = b,a+b
return result
fib2(100)
#The return statement returns with a value from a function.
#return without an expression arugment returns None.
#The statement result.append(a) calls a method of the list object result.
#A method i a function that belongs to an object and is named obj.methodname
def f(a, L=[]):
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))
print(f(100))
# If you dont want the default to be shared with subsequent calls...
def f(a, L=None):
if L is None:
L = [] # generate a new list every iteration
L.append(a)
return L
print(f(0))
print(f(1))
print(f(2))
print(f(100))
## Keyword Arguments ##
# which are of the form: kwarg=value
# In general:
# def func(required, state, action, type):
# lets make one up...
food=['apple', 'organges', 'bread', 'salad']
def store(food, state='need', action='buy', type='cash'):
if food == 'salad':
print('This store has the groceries I', state,',' )
print("but doesn't have", food, )
elif food == 'organges':
print('They have', food, 'but I have insignificant', type,)
store('salad')
# This needs work (not finished)
## The template for writing a function ##
def my_function():
'''Insert a short, concise summary of the object's purpose.'''
pass
print(help(my_function)) # just showing the docstring for the function
name = 'Enter Name Here' # Enter your name here
intro = 'Hello, my name is %s.'%(name)
## Let's do some string minipulation...
# First, lets separate this statement by each space
# we can put each word into a list
List = [word for word in intro.split(" ")]
print(List)
# We can get rid of any punctuation marks with replace
List = [word.replace(".","").replace(",","") for word in intro.split(" ")]
print(List)
# We can print the length of the list (number of words)
print(len(List))
# We can print the length of each element in the list (number of characters)
nChar = 0 # start a count of the number of characters
for i in range(len(List)):
nChar += len(List[i])
print('Word %i/%i has %i characters.'%(i+1,len(List),len(List[i])))
print('The total number of characters in the list is %i'%nChar)
DataFrame
¶import pandas as pd
%matplotlib inline
m = 5 # number of participants or "members"
n = 10 # number of observations of position
observation_times = pd.Series(["01-%0.2i-2020"%i for i in range(n)])
# You can do the same thing using: dates_index = pd.date_range("20200101", periods=m)
array = np.random.random((n,m)) # creating a bunch (n x m) of random samples
samples = pd.DataFrame(array, index=observation_times, columns=["m%i"%i for i in range(m)])
samples
# gather specific memembers
sub_samples = samples[["m2","m4"]] # grabbing only the 2nd and 4th members
sub_samples
sub_samples.sum() # sum up the two columns over all timestamps
# Subtract the element one row up from the current row
subtract = sub_samples.diff(periods=1, axis=0)
subtract.fillna(0)
# Subtract one column with the other
diff = sub_samples.diff(periods=1, axis=1)
diff.fillna(0)
# Another way of getting a subset...
subset = samples[1:4]
subset.plot()
subset.T # transpose the subset
# Create a series of the first day of the year
#series = (subset.T)["01-01-2020"]
# Or you can use...
series = (subset.T)[subset.index[0]]
series
# Delete the last member of this series
series.values