Labels

Tuesday, June 9, 2020

Python notes


import numpy as np
np.power(-1.2,5./3.)
>>>RuntimeWarning: invalid value encountered in power
nan

pow(-1.2,5./3.)
>>>0.6775459407943406-1.173543993917852j
np.seterr(invalid='raise')
try:
	np.power(-1.2,5./3.)
except:
    print('error here')  

def replaceZeroes(data):
  min_nonzero = np.min(data[np.nonzero(data)])
  data[data == 0] = min_nonzero
  return data
  

install numpy for python2.7
sudo apt-get install python-pip # install pip for python2 , will get pip2
/usr/bin/python2.7 -m pip install numpy==1.14.6
python setup.py install --prefix=xxx
Python.h not found
sudo apt-get install python-dev # for python2
sudo apt-get install pythonx-dev # x is version of python, i.e. 3.7
sudo apt-get install python-matplotlib # for python2
sudo apt-get install python-scipy
from scipy.misc import derivative
derivative(exp(x), 1.0, dx=1e-6)
To modify the global variable inside the function, we need add the keyword 'global'
a=0
def fun():
	global a
    a+=1
time
import time
t0=time.time()
time.time() - t0
numpy insert

array=np.insert(array,0,'s')

if any(x>5 for x in range(-2,20)):
	print('one element >5')
fill matrix with same element
np.full((2,2),1)
construct matrix
from scipy.sparse import diags
diagonals = [[1, 2, 3, 4], [1, 2, 3], [1, 2]]
diags(diagonals, [0, -1, 2]).toarray()
diags([1,1],[-1,1],shape=(3,4)).toarray()
print numpy narray nice
def matprint(mat, fmt="g"):
    col_maxes = [max([len(("{:"+fmt+"}").format(x)) for x in col]) for col in mat.T]
    for x in mat:
        for i, y in enumerate(x):
            print(("{:"+str(col_maxes[i])+fmt+"}").format(y), end="  ")
        print("")
print(np.array2string(A, suppress_small=True, formatter={'float': '{:0.4f}'.format}))
pip update package
pip install package-name -U --user


a=[1,2,3,4]
a[1:-1] will give 2,3 doesn't include last element 3!
a[1:4] or a[1:] will give 2,3,4 
a[-1] give 4


a=[2]*number # initialize list with same value 2
b=np.full((1,3),2) #give array([[2, 2, 2]])
b[0] give array([2, 2, 2])
c=np.full((3),2) give array([2, 2, 2])
c[0] give 2

insert one row into numpy array
a=np.zeros((2,2))
#line 1 is the line before to insert, 0 is the axis 
a=np.insert(1,np.array((2,2)),0)
give
array([[ 0.,  0.],
       [ 2.,  2.],
       [ 0.,  0.]])
row_number,col_number = a_array.shape
row_number = len(a_array)
sympy.latex() converts mathematical expressions into Latex equations.

check varible type is numpy.float64
isinstance(numpy.float64(1.3), numpy.float64) 
>>> True
plot odd numbers subplot in matplotlib
fig, axes = plt.subplots(2, 3, figsize=(20, 10))
fig.delaxes(ax=axes(2,2))
we will get 5 subplots. matplotlib subplot tight_layout
fig.tight_layout(rect=[0, 0.03, 1, 0.95])



Reference:
https://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.derivative.html
https://gist.github.com/braingineer/d801735dac07ff3ac4d746e1f218ab75
https://stackoverflow.com/questions/8298797/inserting-a-row-at-a-specific-location-in-a-2d-array-in-numpy

No comments:

Post a Comment