PYTHON

USEFUL LINKS

Signs in Python
Statistics for Python
installing python libraries on mac


RUN A BASH COMMAND WITHIN PYTHON

there are series of commands: os.system(cmd), ospopen(cmd), os.popen2(cmd, mode, bufsize), os.popen3(cmd, mode, bufsize), os.popen3(cmd, mode, bufsize) etc.
for example:

import os
filname="data.out"
bash_command="wc "+ filename+"| awk '{print $1}'"
result_inp_in_file_format=os.popen(bash_command)
result_in_string_format=result_inp_in_file_format.read()

array in python

Very important(from http://www.astro.ufl.edu/~warner/prog/python.html):
Array Dimensions and Subscripts: When creating a multi-dimensional array, the format is ([[depth,] height,] width). Therefore, when accessing array elements in a two dimensional array, the row is listed first, then the column. When accessing an element of a two-dimensional list, the following notation must be used: list[i][j]. However, two dimensional arrays can also use the notation: array[i,j]. In fact, this is the preferred notation of the two for arrays because you cannot use wildcards in the first dimension of the array[i][j] notation (i.e., array[1:3][4] would cause an error whereas array[1:3,4] is valid).

Wildcards can be used in array subscripts using the : , which is known as slicing. This is similar to IDL, with one major difference: if a=[0 1 2 3 4 5], in IDL a[1:4] = [1 2 3 4], but in Python, a[1:4] = [1 2 3]. In Python, when slicing array[i:j], it returns an array containing elements from i to j-1. Just like with strings, indices of arrays can be negative, in which case they count from the right instead of the left, i.e. a[-4:-1] = [2 3 4]. A : can also specify the rest of the elements or up to element, or all elements and arrays or lists can be used to subscript other arrays:
print a[:3] #[0 1 2]
print a[4:] #[4 5]
print a[:] #[0 1 2 3 4 5]
print a[[1,3,4]] #[1 3 4]
Note that slicing in python does not create a new array but just a pointer to the original array. b=a[0:10] followed by b[0] = 5 also changes a[0] to 5. To avoid this, use b = copy(a[0:10])


copy with reference and without reference

The default copying operation is python is by reference


error/exception handling

Errors detected during execution are called exceptions
[[code="Python"]]
try:
<statement(s)>
except Condition1, errmsg:
<statement(s)>
except Condition2:
<statement(s)>

else:
<statement(s)>
finally:
<statement(s)>
[[/code]]
"errmsg" is an optional value to store an error message.

Statement(s) in the optional "finally" section are always run, even if there is an uncaught exception in the "try" section.
example:

while True:
 
   try:
      a=float(input('First number:'))
      b=float(print('Second number:'))
      print('The ratio is {0:g}' ,a/b)
   except ZeroDivisionError:
      print ('Error: Zero division not allowed!! \n')
      print('try again')
      raise
   finally:
      break

random array using numpy

import numpy as np
np.random.random((3,4))

Regular Expression

regular_expression

import re
 
###search and replace: re.sub(pattern, repl, string, max=0)
test='data.out\n'
test=re.sub(r'\s+','',test)
###now test will be 'data.out'

Save Numpy Histogram

data = zip(*np.histogram(ValList,bins))
np.savetxt('test.csv', data, delimeter=',')

Sort Array rows by another array using argsort(index)

from  numpy import  *
arr1 = random.normal( 1, 1,5)
#for example: array([ 0.19955572,  0.80835963,  0.33805017,  0.07317531,  1.02303134])
#arr1.argsort(0)=array([3, 0, 2, 1, 4])
arr2 = random.normal( 1, 1,5)
#for example:  array([ 0.87225647,  1.82409622,  3.36318384, -0.50419292, -0.28474327])
#then sort 
arr2[arr1.argsort(0)[::]]
#array([-0.50419292,  0.87225647,  3.36318384,  1.82409622, -0.28474327])
#or in reverse order (descending)
arr2[arr1.argsort(0)[::-1]]
#array([-0.28474327,  1.82409622,  3.36318384,  0.87225647, -0.50419292])

Sum, Median, Mean (average), Standard Deviation using numpy

import numpy as np
rand_array=np.random.random((3,4))
sum_rand_array=np.sum(rand_array)
median_rand_array=np.median(rand_array)
average_rand_array=np.average(rand_array)
std_rand_array=np.std(rand_array)

Using multiple constructors in a python class

class MultiConstEx():
 def __init__(self,*args):
     if len(args)==3:
         self.load_data(*args)
     elif len(args)==1:
         self.read_orders(*args)

HANDY SCRIPTS for PYTHON

float supporting range function

since range does not support float step. frange can be useful:

def frange(start,stop,step):
    f=start
    while f<stop:
        yield f
        f+=step

Generating a Random list with in a range of two float number

import random
 
x=[random.uniform(float1,float2) for _ in xrange(length_of_list)]

Converting list to array

import numpy as np
np.array(data_list).reshape(num_row, num_col)
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License